'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import LoadingSpinner from '@/components/LoadingSpinner';
import {
    FiChevronLeft, FiPlus, FiEdit2, FiTrash2, FiSearch, 
    FiFilter, FiTerminal, FiBatteryCharging, FiTool, 
    FiAlertCircle, FiPower, FiMapPin, FiX
} from 'react-icons/fi';
import { api } from '@/utils/axios'; // 确保 api 实例已配置
import { AxiosError } from 'axios';

// 与后端实体 ChargingRobot.java 对齐的接口
interface ChargingRobot {
    id: number; // 后端是 Long，TS 中用 number
    robotUid: string;
    status: string; // 例如 "IDLE", "CHARGING"
    batteryLevel?: number | null; 
    currentLocation?: string | null;
    lastHeartbeatTime?: string | null; // Date 类型在 JSON 中通常是 string
    createTime?: string;
    updateTime?: string;
    currentTaskId?: number | null;
}

// 后端分页响应结构 (简化版，关注核心字段)
interface Page<T> {
    records: T[];
    total: number;
    size: number;
    current: number;
    pages: number;
}

// 机器人查询请求参数接口 (对应 ChargingRobotQueryRequest.java)
interface ChargingRobotQueryRequest {
    current: number;
    pageSize: number;
    robotUid?: string;
    status?: string; // 'ALL' 表示不按状态筛选，实际发送时空字符串或不传此字段
    sortField?: string;
    sortOrder?: 'ascend' | 'descend';
}

// 在 ChargingRobotQueryRequest 定义之后，添加 BaseResponse 接口定义 (如果它还没有在全局定义的话)
// 这个定义应该与你的后端 common.BaseResponse 一致
interface BaseResponse<T> {
    code: number;
    data: T;
    message?: string;
}

// Backend request for adding a robot (assuming structure)
interface ChargingRobotAddRequest {
    robotUid: string;
    status: string; 
    batteryLevel?: number | null;
    currentLocation?: string | null;
}

// For Editing Robot - includes ID
interface ChargingRobotUpdateRequest {
    id: number;
    robotUid?: string; // UID might not be editable, but included based on backend DTO
    status?: string;
    batteryLevel?: number | null;
    currentLocation?: string | null;
}

// Interface for Delete Request (matches backend's DeleteRequest)
interface DeleteRobotRequest {
    id: number;
}

const getRobotStatusDisplay = (status: string | undefined | null) => {
    if (!status) return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">未知</span>;
    switch (status.toUpperCase()) {
        case 'IDLE':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"><FiPower className="mr-1" /> 空闲</span>;
        case 'CHARGING':
        case 'CHARGING_IN_PROGRESS': // 兼容可能的枚举值
        case 'CHARGING_STARTED':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"><FiBatteryCharging className="mr-1" /> 充电中</span>;
        case 'MAINTENANCE':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"><FiTool className="mr-1" /> 维护中</span>;
        case 'ERROR':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800"><FiAlertCircle className="mr-1" /> 故障</span>;
        case 'OFFLINE':
             return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-200 text-gray-700"><FiAlertCircle className="mr-1" /> 离线</span>; // Adjusted colors for offline
        case 'MOVING':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800"><FiTerminal className="mr-1" /> 移动中</span>;
        default:
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">{status}</span>;
    }
};

export default function AdminRobotsPage() {
    const { user, isAuthenticated, isLoading: authLoading } = useAuth();
    const router = useRouter();
    
    const [robots, setRobots] = useState<ChargingRobot[]>([]);
    const [robotStatusTypes, setRobotStatusTypes] = useState<string[]>([]);
    const [pageInfo, setPageInfo] = useState<Omit<Page<ChargingRobot>, 'records'>>({
        current: 1,
        size: 10, 
        total: 0,
        pages: 0,
    });
    const [filters, setFilters] = useState<{
        robotUid: string;
        status: string; // 'ALL' or actual status value
    }>({ robotUid: '', status: 'ALL' });
    
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    // State for Add Robot Modal
    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const defaultAddRobotData: ChargingRobotAddRequest = {
        robotUid: '',
        status: 'IDLE',
        batteryLevel: null, // Default to null or a sensible number like 100
        currentLocation: ''
    };
    const [newRobotData, setNewRobotData] = useState<ChargingRobotAddRequest>(defaultAddRobotData);
    const [addError, setAddError] = useState<string | null>(null);

    // State for Delete Robot Modal
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const [robotToDelete, setRobotToDelete] = useState<ChargingRobot | null>(null);
    const [deleteError, setDeleteError] = useState<string | null>(null);
    const [isDeletingRobot, setIsDeletingRobot] = useState(false);

    // State for Edit Robot Modal
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [robotToEditData, setRobotToEditData] = useState<ChargingRobotUpdateRequest | null>(null);
    const [editError, setEditError] = useState<string | null>(null);
    const [isEditingRobot, setIsEditingRobot] = useState(false);

    // 认证和权限检查
    useEffect(() => {
        if (!authLoading && !isAuthenticated) {
            router.replace('/login');
            return;
        }
        if (isAuthenticated && user?.role !== 'admin') {
            router.replace('/dashboard');
        }
    }, [authLoading, isAuthenticated, user, router]);

    // 获取机器人状态类型
    const fetchRobotStatusTypes = useCallback(async () => {
        try {
            const response = await api.get<BaseResponse<string[]>>('/api/admin/robot/status/types'); 
            if (response.data && response.data.code === 0 && Array.isArray(response.data.data)) {
                setRobotStatusTypes(response.data.data);
                // If newRobotData.status is default and status types are loaded, set to the first available status
                if (newRobotData.status === 'IDLE' && response.data.data.length > 0) {
                    setNewRobotData(prev => ({ ...prev, status: response.data.data[0] }));
                } else if (response.data.data.length === 0 && newRobotData.status !== 'IDLE') {
                     setNewRobotData(prev => ({ ...prev, status: 'IDLE' })); // Fallback if no types
                }
            } else {
                console.error("Failed to fetch robot status types or data format is incorrect:", response.data);
                setRobotStatusTypes([]); 
                setNewRobotData(prev => ({ ...prev, status: 'IDLE' })); // Fallback
            }
        } catch (err) {
            console.error("API error fetching robot status types:", err);
            setRobotStatusTypes([]); 
            setNewRobotData(prev => ({ ...prev, status: 'IDLE' })); // Fallback
        }
    }, [newRobotData.status]); // Added newRobotData.status to dependencies to re-evaluate default

    // 获取机器人列表
    const fetchRobots = useCallback(async (currentPage: number, currentPageSize: number, currentFilters: typeof filters) => {
        if (!isAuthenticated || user?.role !== 'admin') return;
        setIsLoading(true);
        setError(null);

        const queryParams: ChargingRobotQueryRequest = {
            current: currentPage,
            pageSize: currentPageSize,
            robotUid: currentFilters.robotUid || undefined, 
            status: currentFilters.status === 'ALL' ? undefined : currentFilters.status, 
            sortField: 'create_time', 
            sortOrder: 'descend',
        };

        try {
            // Correctly expect BaseResponse wrapping Page<ChargingRobot>
            const response = await api.post<BaseResponse<Page<ChargingRobot>>>('/api/admin/robot/list/page', queryParams);
            
            if (response.data && response.data.code === 0 && response.data.data) {
                const pageData = response.data.data; // This is the Page<ChargingRobot> object
                setRobots(pageData.records || []);
                setPageInfo({
                    current: pageData.current,
                    size: pageData.size,
                    total: pageData.total,
                    pages: pageData.pages,
                });
            } else {
                console.error("Failed to fetch robots or data format is incorrect:", response.data);
                setError(response.data?.message || "加载机器人列表失败，数据格式不正确。");
                setRobots([]);
                setPageInfo(prev => ({ ...prev, total: 0, pages: 0, current: 1 }));
            }
        } catch (err) {
            console.error("Failed to fetch robots:", err);
            const axiosError = err as AxiosError;
            if (axiosError.response) {
                setError(`加载机器人列表失败: ${axiosError.response.status} ${(axiosError.response.data as any)?.message || axiosError.message}`);
            } else if (axiosError.request) {
                setError("加载机器人列表失败: 未收到服务器响应。");
            } else {
                setError(`加载机器人列表失败: ${axiosError.message}`);
            }
            setRobots([]); 
            setPageInfo(prev => ({ ...prev, total:0, pages:0, current: 1})); 
        }
        setIsLoading(false);
    }, [isAuthenticated, user?.role]);

    // 初始加载和当认证通过时加载
    useEffect(() => {
        if (isAuthenticated && user?.role === 'admin') {
            fetchRobotStatusTypes();
            fetchRobots(pageInfo.current, pageInfo.size, filters); 
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isAuthenticated, user?.role]); // 依赖于认证状态，确保只在管理员登录后执行
    // fetchRobots 和 fetchRobotStatusTypes 使用 useCallback 固化，不需要加入依赖

    // 处理筛选条件或分页变化
    const handleFilterChange = () => {
        // 重置到第一页进行新的筛选
        fetchRobots(1, pageInfo.size, filters);
    };

    const handlePageChange = (newPage: number) => {
        fetchRobots(newPage, pageInfo.size, filters);
    };
    
    const handleOpenAddModal = () => {
        setNewRobotData({ ...defaultAddRobotData, status: robotStatusTypes.length > 0 ? robotStatusTypes[0] : 'IDLE' });
        setAddError(null);
        setIsAddModalOpen(true);
    };

    const handleAddRobotSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setAddError(null);
        if (!newRobotData.robotUid) {
            setAddError("机器人UID不能为空。");
            return;
        }
        if (!newRobotData.status) {
            setAddError("机器人状态不能为空。");
            return;
        }

        // Battery level validation (example)
        if (newRobotData.batteryLevel !== null && newRobotData.batteryLevel !== undefined) {
            const battery = Number(newRobotData.batteryLevel);
            if (isNaN(battery) || battery < 0 || battery > 100) {
                setAddError("电池电量必须是0到100之间的数字。");
                return;
            }
        }

        setIsLoading(true); // Or a specific loading state like setIsAddingRobot(true)
        try {
            const response = await api.post<BaseResponse<ChargingRobot>>('/api/admin/robot/add', newRobotData);
            if (response.data && response.data.code === 0) {
                setIsAddModalOpen(false);
                fetchRobots(pageInfo.current, pageInfo.size, filters); // Refresh list
            } else {
                setAddError(response.data.message || "添加机器人失败，请重试。");
            }
        } catch (err) {
            const axiosError = err as AxiosError;
            console.error("Error adding robot:", axiosError);
            if (axiosError.response && axiosError.response.data && typeof (axiosError.response.data as any).message === 'string') {
                setAddError((axiosError.response.data as any).message);
            } else {
                setAddError("添加机器人失败，发生未知错误。");
            }
        }
        setIsLoading(false);
    };

    // Handlers for Delete Robot Modal
    const handleOpenDeleteModal = (robot: ChargingRobot) => {
        setRobotToDelete(robot);
        setDeleteError(null);
        setIsDeleteModalOpen(true);
    };

    const handleDeleteRobotSubmit = async () => {
        if (!robotToDelete) return;
        setIsDeletingRobot(true);
        setDeleteError(null);
        try {
            const deletePayload: DeleteRobotRequest = { id: robotToDelete.id };
            const response = await api.post<BaseResponse<boolean>>('/api/admin/robot/delete', deletePayload);
            if (response.data && response.data.code === 0 && response.data.data === true) {
                setIsDeleteModalOpen(false);
                setRobotToDelete(null);
                // Refresh list. If current page becomes empty after deletion, try to go to previous page or first page.
                const newTotal = pageInfo.total - 1;
                const newPages = Math.ceil(newTotal / pageInfo.size);
                let newCurrentPage = pageInfo.current;
                if (robots.length === 1 && pageInfo.current > 1) { // If it was the last item on a page > 1
                    newCurrentPage = pageInfo.current - 1;
                }
                if (newTotal === 0) { // if list becomes empty
                    newCurrentPage = 1;
                }
                fetchRobots(newCurrentPage, pageInfo.size, filters); 
                // Optionally: Show success toast
            } else {
                setDeleteError(response.data?.message || "删除机器人失败。");
            }
        } catch (err) {
            console.error("Failed to delete robot:", err);
            const axiosError = err as AxiosError;
            if (axiosError.response) {
                setDeleteError(`删除失败: ${(axiosError.response.data as any)?.message || axiosError.message}`);
            } else {
                setDeleteError("删除机器人失败，请稍后再试。");
            }
        }
        setIsDeletingRobot(false);
    };

    // Handlers for Edit Robot Modal
    const handleOpenEditModal = (robot: ChargingRobot) => {
        setRobotToEditData({
            id: robot.id,
            robotUid: robot.robotUid,
            status: robot.status,
            batteryLevel: robot.batteryLevel,
            currentLocation: robot.currentLocation || '',
        });
        setEditError(null);
        setIsEditModalOpen(true);
    };

    const handleEditRobotSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!robotToEditData) return;
        setEditError(null);

        // Validate battery level
        if (robotToEditData.batteryLevel !== null && robotToEditData.batteryLevel !== undefined) {
            const battery = Number(robotToEditData.batteryLevel);
            if (isNaN(battery) || battery < 0 || battery > 100) {
                setEditError("电池电量必须是0到100之间的数字。");
                return;
            }
        }

        setIsEditingRobot(true);
        try {
            // Ensure robotToEditData has the ID
            const payload: ChargingRobotUpdateRequest = {
                id: robotToEditData.id, // ID is crucial
                robotUid: robotToEditData.robotUid, // UID might be part of the form or fixed
                status: robotToEditData.status,
                batteryLevel: robotToEditData.batteryLevel,
                currentLocation: robotToEditData.currentLocation,
            };
            const response = await api.post<BaseResponse<null>>('/api/admin/robot/update', payload);
            if (response.data && response.data.code === 0) {
                setIsEditModalOpen(false);
                fetchRobots(pageInfo.current, pageInfo.size, filters); // Refresh list
            } else {
                setEditError(response.data.message || "更新机器人失败，请重试。");
            }
        } catch (err) {
            const axiosError = err as AxiosError;
            console.error("Error updating robot:", axiosError);
            if (axiosError.response && axiosError.response.data && typeof (axiosError.response.data as any).message === 'string') {
                setEditError((axiosError.response.data as any).message);
            } else {
                setEditError("更新机器人失败，发生未知错误。");
            }
        }
        setIsEditingRobot(false);
    };

    // 权限未加载或用户非管理员时显示加载
    if (authLoading || !isAuthenticated || (isAuthenticated && user?.role !== 'admin')) {
        return <LoadingSpinner />;
    }

    return (
        <div className="min-h-screen bg-gray-100 p-4 md:p-6 lg:p-8">
            <div className="max-w-7xl mx-auto">
                <header className="mb-6 md:mb-8">
                    <div className="flex flex-col md:flex-row items-start md:items-center justify-between">
                        <h1 className="text-2xl md:text-3xl font-bold text-gray-800 flex items-center mb-4 md:mb-0">
                            <FiTerminal className="mr-3 text-indigo-600" /> 机器人管理
                        </h1>
                        <Link 
                            href="/admin/dashboard" 
                            legacyBehavior={false}
                            className="flex items-center text-sm text-indigo-600 hover:text-indigo-800 font-medium"
                        >
                            <FiChevronLeft className="mr-1" /> 返回管理员控制台
                        </Link>
                    </div>
                </header>

                {/* Filters and Actions */}
                <div className="mb-6 p-4 bg-white rounded-xl shadow-md">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                        <div>
                            <label htmlFor="searchRobotUid" className="block text-sm font-medium text-gray-700 mb-1">
                                <FiSearch className="inline mr-1" /> 搜索UID
                            </label>
                            <input
                                type="text"
                                id="searchRobotUid"
                                placeholder="RBT-xxxx"
                                className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                value={filters.robotUid}
                                onChange={(e) => setFilters(prev => ({ ...prev, robotUid: e.target.value }))}
                                onKeyDown={(e) => e.key === 'Enter' && handleFilterChange()} // 支持回车搜索
                            />
                        </div>
                        <div>
                            <label htmlFor="statusFilter" className="block text-sm font-medium text-gray-700 mb-1">
                                <FiFilter className="inline mr-1" /> 按状态筛选
                            </label>
                            <select
                                id="statusFilter"
                                className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                value={filters.status}
                                onChange={(e) => setFilters(prev => ({ ...prev, status: e.target.value }))}
                            >
                                <option value="ALL">所有状态</option>
                                {robotStatusTypes.map(statusType => (
                                    <option key={statusType} value={statusType}>{getRobotStatusDisplay(statusType)}</option>
                                ))}
                            </select>
                        </div>
                        <div className="flex space-x-2 items-end">
                            <button 
                                onClick={handleFilterChange} 
                                className="w-full md:w-auto inline-flex items-center justify-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                            >
                                应用筛选
                            </button>
                            <button 
                                onClick={handleOpenAddModal} // Changed to open modal
                                className="w-full md:w-auto inline-flex items-center justify-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                            >
                                <FiPlus className="mr-2 -ml-1 h-5 w-5" /> 添加机器人
                            </button>
                        </div>
                    </div>
                </div>

                {isLoading && !robots.length ? (
                    <LoadingSpinner />
                ) : error ? (
                    <div className="text-center py-12 bg-white rounded-xl shadow-lg">
                        <FiAlertCircle size={48} className="mx-auto text-red-500 mb-4" />
                        <h3 className="text-xl font-medium text-red-700">加载失败</h3>
                        <p className="text-sm text-gray-600 mt-1">{error}</p>
                    </div>
                ) : robots.length > 0 ? (
                    <div className="bg-white rounded-xl shadow-lg overflow-x-auto">
                        <table className="min-w-full divide-y divide-gray-200">
                            <thead className="bg-gray-50">
                                <tr>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">UID</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">电量</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">位置</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最近心跳</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务ID</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {robots.map((robot) => (
                                    <tr key={robot.id}>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">{robot.robotUid}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm">{getRobotStatusDisplay(robot.status)}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                            {robot.batteryLevel != null ? (
                                                <div className="flex items-center">
                                                    <div className="w-20 bg-gray-200 rounded-full h-2.5 dark:bg-gray-700 mr-2">
                                                        <div 
                                                            className={`h-2.5 rounded-full ${robot.batteryLevel < 20 ? 'bg-red-500' : robot.batteryLevel < 50 ? 'bg-yellow-400' : 'bg-green-500'}`} 
                                                            style={{ width: `${robot.batteryLevel}%` }}
                                                        ></div>
                                                    </div>
                                                    <span className="text-xs">{robot.batteryLevel}%</span>
                                                </div>
                                            ) : 'N/A'}
                                        </td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500"><FiMapPin className="inline mr-1"/>{robot.currentLocation || 'N/A'}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{robot.lastHeartbeatTime ? new Date(robot.lastHeartbeatTime).toLocaleString() : 'N/A'}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{robot.currentTaskId || 'N/A'}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm font-medium space-x-2">
                                            <button onClick={() => handleOpenEditModal(robot)} className="text-indigo-600 hover:text-indigo-900"><FiEdit2 size={16}/></button>
                                            <button onClick={() => handleOpenDeleteModal(robot)} className="text-red-600 hover:text-red-900"><FiTrash2 size={16}/></button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                ) : (
                    <div className="text-center py-12 bg-white rounded-xl shadow-lg">
                        <FiTerminal size={48} className="mx-auto text-gray-400 mb-4" />
                        <h3 className="text-xl font-medium text-gray-700">未找到机器人</h3>
                        <p className="text-sm text-gray-500 mt-1">
                            {filters.robotUid || filters.status !== 'ALL' ? '没有机器人符合当前筛选条件。' : '系统中暂无机器人记录，请先添加。'}
                        </p>
                    </div>
                )}

                {/* Pagination Controls - Server-side */}
                {pageInfo.total > 0 && (
                    <div className="mt-6 flex justify-center items-center space-x-2">
                        <button
                            onClick={() => handlePageChange(pageInfo.current - 1)}
                            disabled={pageInfo.current <= 1 || isLoading}
                            className="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            上一页
                        </button>
                        {[...Array(pageInfo.pages).keys()].map(number => (
                            <button
                                key={number + 1}
                                onClick={() => handlePageChange(number + 1)}
                                disabled={isLoading}
                                className={`px-3 py-1 text-sm border rounded-md ${pageInfo.current === number + 1 ? 'bg-indigo-600 text-white border-indigo-600' : 'border-gray-300 hover:bg-gray-50 disabled:cursor-not-allowed'}`}
                            >
                                {number + 1}
                            </button>
                        ))}
                        <button
                            onClick={() => handlePageChange(pageInfo.current + 1)}
                            disabled={pageInfo.current >= pageInfo.pages || isLoading}
                            className="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            下一页
                        </button>
                         <span className="text-sm text-gray-600">共 {pageInfo.total} 条记录</span>
                    </div>
                )}
            </div>

            {/* Add Robot Modal */}
            {isAddModalOpen && (
                <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full flex items-center justify-center z-50">
                    <div className="relative p-8 bg-white w-full max-w-md m-auto flex-col flex rounded-lg shadow-xl">
                        <div className="flex justify-between items-center mb-6">
                            <h2 className="text-xl font-semibold text-gray-800">添加新机器人</h2>
                            <button onClick={() => setIsAddModalOpen(false)} className="text-gray-400 hover:text-gray-600">
                                <FiX size={24} />
                            </button>
                        </div>
                        
                        <form onSubmit={handleAddRobotSubmit}>
                            <div className="mb-4">
                                <label htmlFor="addRobotUid" className="block text-sm font-medium text-gray-700 mb-1">机器人UID</label>
                                <input
                                    type="text"
                                    id="addRobotUid"
                                    required
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                                    value={newRobotData.robotUid}
                                    onChange={(e) => setNewRobotData({ ...newRobotData, robotUid: e.target.value })}
                                />
                            </div>
                            <div className="mb-4">
                                <label htmlFor="addRobotStatus" className="block text-sm font-medium text-gray-700 mb-1">初始状态</label>
                                <select
                                    id="addRobotStatus"
                                    required
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                                    value={newRobotData.status}
                                    onChange={(e) => setNewRobotData({ ...newRobotData, status: e.target.value })}
                                >
                                    {robotStatusTypes.length > 0 ? robotStatusTypes.map(status => (
                                        <option key={`add-${status}`} value={status}>{getRobotStatusDisplay(status)}</option>
                                    )) : (
                                        <option value="IDLE">{getRobotStatusDisplay('IDLE')}</option> 
                                    )}
                                    {!robotStatusTypes.includes('IDLE') && <option value="IDLE">{getRobotStatusDisplay('IDLE')}</option>}
                                    {!robotStatusTypes.includes('MAINTENANCE') && <option value="MAINTENANCE">{getRobotStatusDisplay('MAINTENANCE')}</option>}
                                </select>
                            </div>
                            <div className="mb-4">
                                <label htmlFor="addBatteryLevel" className="block text-sm font-medium text-gray-700 mb-1">电池电量 (%)</label>
                                <input
                                    type="number"
                                    id="addBatteryLevel"
                                    min="0" max="100"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                                    value={newRobotData.batteryLevel == null ? '' : newRobotData.batteryLevel}
                                    onChange={(e) => setNewRobotData({ ...newRobotData, batteryLevel: e.target.value === '' ? null : parseInt(e.target.value, 10) })}
                                />
                            </div>
                            <div className="mb-6">
                                <label htmlFor="addCurrentLocation" className="block text-sm font-medium text-gray-700 mb-1">当前位置</label>
                                <input
                                    type="text"
                                    id="addCurrentLocation"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                                    value={newRobotData.currentLocation || ''}
                                    onChange={(e) => setNewRobotData({ ...newRobotData, currentLocation: e.target.value })}
                                />
                            </div>

                            {addError && (
                                <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md text-sm">
                                    {addError}
                                
                                </div>
                            )}

                            <div className="flex justify-end space-x-3">
                                <button 
                                    type="button" 
                                    onClick={() => setIsAddModalOpen(false)}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"
                                >
                                    取消
                                </button>
                                <button 
                                    type="submit"
                                    className="px-4 py-2 text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                >
                                    确认添加
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Edit Robot Modal */}
            {isEditModalOpen && robotToEditData && (
                <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full flex items-center justify-center z-50">
                    <div className="relative p-8 bg-white w-full max-w-md m-auto flex-col flex rounded-lg shadow-xl">
                        <div className="flex justify-between items-center mb-6">
                            <h2 className="text-xl font-semibold text-gray-800">编辑机器人信息</h2>
                            <button onClick={() => { setIsEditModalOpen(false); setRobotToEditData(null); }} className="text-gray-400 hover:text-gray-600">
                                <FiX size={24} />
                            </button>
                        </div>
                        
                        <form onSubmit={handleEditRobotSubmit}>
                            <div className="mb-4">
                                <label htmlFor="editRobotUid" className="block text-sm font-medium text-gray-700 mb-1">机器人UID (不可修改)</label>
                                <input
                                    type="text"
                                    id="editRobotUid"
                                    readOnly
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100 cursor-not-allowed"
                                    value={robotToEditData.robotUid || ''}
                                />
                            </div>
                            <div className="mb-4">
                                <label htmlFor="editRobotStatus" className="block text-sm font-medium text-gray-700 mb-1">状态</label>
                                <select
                                    id="editRobotStatus"
                                    required
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                                    value={robotToEditData.status}
                                    onChange={(e) => setRobotToEditData({ ...robotToEditData, status: e.target.value })}
                                >
                                    {robotStatusTypes.map(status => (
                                        <option key={`edit-${status}`} value={status}>{getRobotStatusDisplay(status)}</option>
                                    ))}
                                    {!robotStatusTypes.includes('IDLE') && <option value="IDLE">{getRobotStatusDisplay('IDLE')}</option>}
                                    {!robotStatusTypes.includes('MAINTENANCE') && <option value="MAINTENANCE">{getRobotStatusDisplay('MAINTENANCE')}</option>}
                                </select>
                            </div>
                            <div className="mb-4">
                                <label htmlFor="editBatteryLevel" className="block text-sm font-medium text-gray-700 mb-1">电池电量 (%)</label>
                                <input
                                    type="number"
                                    id="editBatteryLevel"
                                    min="0" max="100"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                                    value={robotToEditData.batteryLevel == null ? '' : robotToEditData.batteryLevel}
                                    onChange={(e) => setRobotToEditData({ ...robotToEditData, batteryLevel: e.target.value === '' ? null : parseInt(e.target.value, 10) })}
                                />
                            </div>
                            <div className="mb-6">
                                <label htmlFor="editCurrentLocation" className="block text-sm font-medium text-gray-700 mb-1">当前位置</label>
                                <input
                                    type="text"
                                    id="editCurrentLocation"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                                    value={robotToEditData.currentLocation || ''}
                                    onChange={(e) => setRobotToEditData({ ...robotToEditData, currentLocation: e.target.value })}
                                />
                            </div>

                            {editError && (
                                <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md text-sm">
                                    {editError}
                                </div>
                            )}
                            <div className="flex justify-end space-x-3">
                                <button 
                                    type="button" 
                                    onClick={() => { setIsEditModalOpen(false); setRobotToEditData(null); }}
                                    disabled={isEditingRobot}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 disabled:opacity-50"
                                >
                                    取消
                                </button>
                                <button 
                                    type="submit"
                                    disabled={isEditingRobot}
                                    className="px-4 py-2 text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
                                >
                                    {isEditingRobot ? '保存中...' : '保存更改'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Delete Robot Modal */}
            {isDeleteModalOpen && robotToDelete && (
                <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full flex items-center justify-center z-50">
                    <div className="relative p-8 bg-white w-full max-w-md m-auto flex-col flex rounded-lg shadow-xl">
                        <div className="flex justify-between items-center mb-4">
                            <h2 className="text-xl font-semibold text-gray-800">确认删除</h2>
                            <button onClick={() => { setIsDeleteModalOpen(false); setRobotToDelete(null); }} className="text-gray-400 hover:text-gray-600">
                                <FiX size={24} />
                            </button>
                        </div>
                        <p className="text-gray-600 text-sm mb-6">
                            您确定要删除机器人 <span className="font-semibold">{robotToDelete.robotUid}</span> 吗？此操作无法撤销。
                        </p>
                        {deleteError && (
                            <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md text-sm">
                                {deleteError}
                            </div>
                        )}
                        <div className="flex justify-end space-x-3">
                            <button 
                                type="button" 
                                onClick={() => { setIsDeleteModalOpen(false); setRobotToDelete(null); }}
                                disabled={isDeletingRobot}
                                className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 disabled:opacity-50"
                            >
                                取消
                            </button>
                            <button 
                                type="button" // Changed to button, onSubmit is handled by the modal's primary action button
                                onClick={handleDeleteRobotSubmit}
                                disabled={isDeletingRobot}
                                className="px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50"
                            >
                                {isDeletingRobot ? '删除中...' : '确认删除'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
} 