'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { api } from '@/services/api'; 
import LoadingSpinner from '@/components/LoadingSpinner';
import Modal from '@/components/Modal';
import Link from 'next/link';
// AuthenticatedLayout is likely applied via the directory structure (app/(authenticated)/layout.tsx)
// So, no explicit import should be needed here for wrapping the page content.

// Define interfaces for ParkingSpot and query params based on backend DTOs
interface ParkingSpot {
  id: number;
  spotUid: string;
  locationDesc: string | null;
  status: string; // e.g., AVAILABLE, OCCUPIED, MAINTENANCE, RESERVED
  robotAssignable: boolean;
  currentSessionId: number | null;
  createTime: string;
  updateTime: string;
}

interface ParkingSpotQueryRequest {
  spotUid?: string;
  status?: string;
  robotAssignable?: boolean | string; // Allow string for 'ALL' option in select
  current?: number;
  pageSize?: number;
  sortField?: string;
  sortOrder?: string; // asc or desc
}

// Define interface for Add Parking Spot Request based on backend DTO
interface ParkingSpotAddRequest {
  spotUid: string;
  locationDesc?: string;
  status: string; // Default to AVAILABLE
  robotAssignable: boolean; // Default to true
}

// Define interface for Update Parking Spot Request based on backend DTO
interface ParkingSpotUpdateRequest {
  id: number; // Crucial for identifying the spot to update
  spotUid?: string; // Usually not updatable, but depends on backend logic
  locationDesc?: string;
  status?: string;
  robotAssignable?: boolean;
}

const AdminParkingSpotsPage = () => {
  const { user, isLoading: authLoading } = useAuth();
  const router = useRouter();
  const [isAdmin, setIsAdmin] = useState(false);

  const [parkingSpots, setParkingSpots] = useState<ParkingSpot[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [totalSpots, setTotalSpots] = useState(0);

  // State for query params and pagination
  const [queryParams, setQueryParams] = useState<ParkingSpotQueryRequest>({
    current: 1,
    pageSize: 10,
    sortField: 'create_time',
    sortOrder: 'desc',
  });

  // --- Notification State --- 
  const [notification, setNotification] = useState<{ type: 'success' | 'error'; message: string } | null>(null);

  const showNotification = (message: string, type: 'success' | 'error') => {
    setNotification({ message, type });
    setTimeout(() => {
      setNotification(null);
    }, 3000); // Notification disappears after 3 seconds
  };

  // CRUD Modal States (Add, Edit, Delete)
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [newSpotData, setNewSpotData] = useState<ParkingSpotAddRequest>({
    spotUid: '',
    locationDesc: '',
    status: 'AVAILABLE',
    robotAssignable: true,
  });
  const [addSpotLoading, setAddSpotLoading] = useState(false);
  const [addSpotError, setAddSpotError] = useState<string | null>(null);

  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editingSpot, setEditingSpot] = useState<ParkingSpotUpdateRequest | null>(null);
  const [editSpotLoading, setEditSpotLoading] = useState(false);
  const [editSpotError, setEditSpotError] = useState<string | null>(null);

  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
  const [deletingSpotInfo, setDeletingSpotInfo] = useState<{ id: number; spotUid: string } | null>(null);
  const [deleteSpotLoading, setDeleteSpotLoading] = useState(false);
  const [deleteSpotError, setDeleteSpotError] = useState<string | null>(null);

  // Search/Filter states
  const [searchSpotUid, setSearchSpotUid] = useState('');
  const [searchStatus, setSearchStatus] = useState('');
  const [searchRobotAssignable, setSearchRobotAssignable] = useState('');

  useEffect(() => {
    if (!authLoading) {
      if (!user) {
        router.push('/login');
      } else {
        // Updated admin check based on user.role
        const isAdminUser = user?.role === 'admin'; 
        setIsAdmin(isAdminUser);
        if (!isAdminUser) {
          router.push('/dashboard'); // Redirect non-admins
        }
      }
    }
  }, [user, authLoading, router]); // Removed checkAdmin from dependencies

  const fetchParkingSpots = useCallback(async (overrideParams?: Partial<ParkingSpotQueryRequest>) => {
    if (!isAdmin) return; // Don't fetch if not admin
    setLoading(true);
    setError(null);
    
    const currentSearchParams: ParkingSpotQueryRequest = {
      ...queryParams,
      spotUid: searchSpotUid.trim() || undefined,
      status: searchStatus || undefined,
      robotAssignable: searchRobotAssignable === '' ? undefined : searchRobotAssignable === 'true',
      ...overrideParams, // Apply overrides, e.g., for page changes or new searches
    };

    // Remove undefined keys to keep the request clean
    Object.keys(currentSearchParams).forEach(key => 
      (currentSearchParams as any)[key] === undefined && delete (currentSearchParams as any)[key]
    );

    try {
      const response = await api.post('/admin/spot/list/page', currentSearchParams);
      if (response.data && response.data.code === 0) {
        setParkingSpots(response.data.data.records || []);
        setTotalSpots(response.data.data.total || 0);
        // Update queryParams state if overrideParams were passed (e.g. page change)
        // but not for initial search filter application as that's handled by search button
        if (overrideParams && Object.keys(overrideParams).length > 0 && !overrideParams.spotUid && !overrideParams.status && !overrideParams.robotAssignable ){
            setQueryParams(prev => ({...prev, ...overrideParams}));
        }
      } else {
        setError(response.data.message || '获取车位列表失败');
        setParkingSpots([]);
        setTotalSpots(0);
      }
    } catch (err: any) {
      console.error('获取车位列表错误:', err);
      setError(err.message || '发生未知错误。');
      setParkingSpots([]);
      setTotalSpots(0);
    }
    setLoading(false);
  }, [isAdmin, queryParams, searchSpotUid, searchStatus, searchRobotAssignable]); // Added search states to dependencies

  useEffect(() => {
    if (isAdmin) { // Only fetch if confirmed admin
      fetchParkingSpots();
    }
  }, [fetchParkingSpots, isAdmin]);

  const handlePageChange = (newPage: number) => {
    fetchParkingSpots({ current: newPage });
    setQueryParams(prev => ({ ...prev, current: newPage })); // Keep queryParams state in sync for display/logic
  };

  const handlePageSizeChange = (newSize: number) => {
    fetchParkingSpots({ pageSize: newSize, current: 1 });
    setQueryParams(prev => ({ ...prev, pageSize: newSize, current: 1 })); // Reset to first page
  };

  // --- Table Sorting ---
  const handleSort = (fieldKey: keyof ParkingSpot) => {
    // Map frontend display key (camelCase) to backend sortField (snake_case)
    let sortFieldForBackend = '';
    if (fieldKey === 'createTime') {
      sortFieldForBackend = 'create_time';
    } else if (fieldKey === 'updateTime') {
      sortFieldForBackend = 'update_time';
    } else if (fieldKey === 'spotUid') {
        sortFieldForBackend = 'spot_uid'; // example if spot_uid in DB
    } else {
      sortFieldForBackend = fieldKey; // For other fields like status, robotAssignable if they are directly mapped
    }

    const newSortOrder = queryParams.sortField === sortFieldForBackend && queryParams.sortOrder === 'asc' ? 'desc' : 'asc';
    const newQueryParams = { ...queryParams, sortField: sortFieldForBackend, sortOrder: newSortOrder, current: 1 };
    setQueryParams(newQueryParams);
    fetchParkingSpots(newQueryParams);
  };

  // --- Search/Filter Logic --- 
  const handleSearch = () => {
    const newQueryParams = { 
        ...queryParams, // Keep current sort and page size
        current: 1, 
        spotUid: searchSpotUid.trim() || undefined,
        status: searchStatus || undefined,
        robotAssignable: searchRobotAssignable === '' ? undefined : searchRobotAssignable === 'true',
    };
    setQueryParams(newQueryParams);
    fetchParkingSpots(newQueryParams); 
  };

  const handleResetSearch = () => {
    setSearchSpotUid('');
    setSearchStatus('');
    setSearchRobotAssignable('');
    const baseParams = {
        current: 1,
        pageSize: queryParams.pageSize, // Retain current page size
        sortField: 'create_time', // Default sort
        sortOrder: 'desc', // Default sort order
        spotUid: undefined,
        status: undefined,
        robotAssignable: undefined,
    }
    setQueryParams(baseParams);
    fetchParkingSpots(baseParams);
  };

  // --- Add New Spot Modal Logic --- 
  const openAddModal = () => {
    setNewSpotData({  // Reset form data
      spotUid: '',
      locationDesc: '',
      status: 'AVAILABLE',
      robotAssignable: true,
    });
    setAddSpotError(null);
    setIsAddModalOpen(true);
  };

  const closeAddModal = () => {
    setIsAddModalOpen(false);
  };

  const handleNewSpotDataChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    const checked = (e.target as HTMLInputElement).checked; // For checkbox

    setNewSpotData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }));
  };

  const handleAddNewSpot = async () => {
    if (!newSpotData.spotUid.trim()) {
      setAddSpotError('车位UID是必填项。');
      return;
    }
    const spotUidRegex = /^[a-zA-Z0-9]{3,20}$/;
    if (!spotUidRegex.test(newSpotData.spotUid.trim())) {
      setAddSpotError('车位UID必须是3-20位字母或数字。');
      return;
    }
    if (newSpotData.locationDesc && newSpotData.locationDesc.length > 200) {
        setAddSpotError('位置描述不能超过200个字符。');
        return;
    }

    setAddSpotLoading(true);
    setAddSpotError(null);
    try {
      const response = await api.post('/admin/spot/add', newSpotData);
      if (response.data && response.data.code === 0) {
        closeAddModal();
        fetchParkingSpots({current: queryParams.current}); 
        showNotification('车位添加成功！', 'success');
      } else {
        setAddSpotError(response.data.message || '添加车位失败。');
        showNotification(response.data.message || '添加车位失败。', 'error');
      }
    } catch (err: any) {
      console.error('添加车位错误:', err);
      setAddSpotError(err.message || '添加车位时发生未知错误。');
      showNotification(err.message || '添加车位时发生未知错误。', 'error');
    }
    setAddSpotLoading(false);
  };

  // --- Edit Spot Modal Logic --- 
  const openEditModal = (spot: ParkingSpot) => {
    setEditingSpot({
      id: spot.id,
      spotUid: spot.spotUid, 
      locationDesc: spot.locationDesc || '',
      status: spot.status,
      robotAssignable: spot.robotAssignable,
    });
    setEditSpotError(null);
    setIsEditModalOpen(true);
  };

  const closeEditModal = () => {
    setIsEditModalOpen(false);
    setEditingSpot(null);
  };

  const handleEditingSpotDataChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    const checked = (e.target as HTMLInputElement).checked;
    setEditingSpot(prev => prev ? { ...prev, [name]: type === 'checkbox' ? checked : value } : null);
  };

  const handleUpdateSpot = async () => {
    if (!editingSpot) return;

    if (editingSpot.locationDesc && editingSpot.locationDesc.length > 200) {
        setEditSpotError('位置描述不能超过200个字符。');
        return;
    }

    setEditSpotLoading(true);
    setEditSpotError(null);
    try {
      const response = await api.post('/admin/spot/update', editingSpot); 
      if (response.data && response.data.code === 0) {
        closeEditModal();
        fetchParkingSpots({current: queryParams.current}); 
        showNotification('车位更新成功！', 'success');
      } else {
        setEditSpotError(response.data.message || '更新车位失败。');
        showNotification(response.data.message || '更新车位失败。', 'error');
      }
    } catch (err: any) {
      console.error('更新车位错误:', err);
      setEditSpotError(err.message || '更新车位时发生未知错误。');
      showNotification(err.message || '更新车位时发生未知错误。', 'error');
    }
    setEditSpotLoading(false);
  };

  // --- Delete Spot Confirmation Logic --- 
  const openDeleteConfirm = (spot: ParkingSpot) => {
    setDeletingSpotInfo({ id: spot.id, spotUid: spot.spotUid });
    setDeleteSpotError(null);
    setIsDeleteConfirmOpen(true);
  };

  const closeDeleteConfirm = () => {
    setIsDeleteConfirmOpen(false);
    setDeletingSpotInfo(null);
  };

  const handleDeleteSpot = async () => {
    if (!deletingSpotInfo) return;
    setDeleteSpotLoading(true);
    setDeleteSpotError(null);
    try {
      const response = await api.post('/admin/spot/delete', { id: deletingSpotInfo.id });
      if (response.data && response.data.code === 0) {
        closeDeleteConfirm();
        // After deletion, decide which page to fetch. If current page becomes empty, fetch previous page or page 1.
        // For simplicity, refetching all or current page based on remaining items.
        const newTotalSpots = totalSpots - 1;
        const newCurrentPage = Math.max(1, Math.ceil(newTotalSpots / (queryParams.pageSize || 10)));
        if (queryParams.current && queryParams.current > newCurrentPage && newCurrentPage > 0) {
          fetchParkingSpots({ current: newCurrentPage });
        } else {
          fetchParkingSpots({current: queryParams.current}); // Or just fetch the current page
        }
        showNotification(`车位 ${deletingSpotInfo.spotUid} 删除成功！`, 'success');
      } else {
        setDeleteSpotError(response.data.message || '删除车位失败。');
        showNotification(response.data.message || '删除车位失败。', 'error');
      }
    } catch (err: any) {
      console.error('删除车位错误:', err);
      setDeleteSpotError(err.message || '删除车位时发生未知错误。');
      showNotification(err.message || '删除车位时发生未知错误。', 'error');
    }
    setDeleteSpotLoading(false);
  };
  
  const SortIndicator: React.FC<{ field: keyof ParkingSpot }> = ({ field }) => {
    // Compare with the backend's expected snake_case field name for active sort column
    let backendSortField = queryParams.sortField;
    if (field === 'createTime' && queryParams.sortField === 'create_time') {
      // Correctly show indicator if frontend 'createTime' maps to backend 'create_time'
    } else if (field === 'updateTime' && queryParams.sortField === 'update_time') {
      // Correctly show indicator if frontend 'updateTime' maps to backend 'update_time'
    } else if (field === 'spotUid' && queryParams.sortField === 'spot_uid') {
      // Correctly show indicator
    } else if (queryParams.sortField !== field) {
      return null; // Not the active sort column (after mapping)
    }
  
    if (queryParams.sortField === (field === 'createTime' ? 'create_time' : field === 'updateTime' ? 'update_time' : field === 'spotUid' ? 'spot_uid' : field)) {
        return queryParams.sortOrder === 'asc' ? <span className="ml-1">▲</span> : <span className="ml-1">▼</span>;
    }
    return null;
  };

  if (authLoading || (!isAdmin && user)) { 
    return <LoadingSpinner />;
  }

  if (!user) { 
    return <p>正在重定向到登录页面...</p>;
  }
  
  if (!isAdmin) { 
    return <p>访问被拒绝。正在重定向...</p>; 
  }

  // Main content for Admin
  return (
    <div className="container mx-auto px-4 py-8 relative">
      {/* Notification Area */} 
      {notification && (
        <div className={`fixed top-5 right-5 p-4 rounded-md shadow-lg text-white z-[100] 
                        ${notification.type === 'success' ? 'bg-green-500' : 'bg-red-500'}`}>
          {notification.message}
        </div>
      )}

      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
            <h1 className="text-3xl font-semibold text-gray-800">管理员：车位管理</h1>
            <Link 
              href="/admin/dashboard" 
              className="bg-gray-500 hover:bg-gray-600 text-white text-sm font-semibold py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-opacity-75"
            >
              返回工作台
            </Link>
        </div>
        <button 
          onClick={openAddModal} // Open the modal
          className="bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out"
        >
          + 新建车位
        </button>
      </div>

      {/* Search and Filter Bar */} 
      <div className="mb-6 p-4 bg-gray-50 rounded-lg shadow">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
          <div>
            <label htmlFor="searchSpotUid" className="block text-sm font-medium text-gray-700">车位UID</label>
            <input 
              type="text"
              name="searchSpotUid"
              id="searchSpotUid"
              value={searchSpotUid}
              onChange={(e) => setSearchSpotUid(e.target.value)}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
            />
          </div>
          <div>
            <label htmlFor="searchStatus" className="block text-sm font-medium text-gray-700">状态</label>
            <select 
              name="searchStatus"
              id="searchStatus"
              value={searchStatus}
              onChange={(e) => setSearchStatus(e.target.value)}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
            >
              <option value="">所有状态</option>
              <option value="AVAILABLE">可用</option>
              <option value="OCCUPIED">占用</option>
              <option value="MAINTENANCE">维护中</option>
              <option value="RESERVED">预留</option>
            </select>
          </div>
          <div>
            <label htmlFor="searchRobotAssignable" className="block text-sm font-medium text-gray-700">机器人可分配</label>
            <select 
              name="searchRobotAssignable"
              id="searchRobotAssignable"
              value={searchRobotAssignable}
              onChange={(e) => setSearchRobotAssignable(e.target.value)}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
            >
              <option value="">全部</option>
              <option value="true">是</option>
              <option value="false">否</option>
            </select>
          </div>
          <div className="flex space-x-2">
            <button 
              onClick={handleSearch}
              className="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            >
              搜索
            </button>
            <button 
              onClick={handleResetSearch}
              className="w-full bg-gray-300 hover:bg-gray-400 text-gray-800 font-semibold py-2 px-4 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"
            >
              重置
            </button>
          </div>
        </div>
      </div>

      {/* Add New Spot Modal */} 
      <Modal 
        isOpen={isAddModalOpen} 
        onClose={closeAddModal} 
        title="添加新车位"
        footer={
          <div className="flex justify-end space-x-2">
            <button 
              onClick={closeAddModal}
              className="px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"
            >
              取消
            </button>
            <button 
              onClick={handleAddNewSpot}
              disabled={addSpotLoading}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
            >
              {addSpotLoading ? '添加中...' : '添加车位'}
            </button>
          </div>
        }
      >
        <form onSubmit={(e) => { e.preventDefault(); handleAddNewSpot(); }}>
          {addSpotError && <p className="text-red-500 text-sm mb-3 bg-red-100 p-2 rounded">{addSpotError}</p>}
          <div className="mb-4">
            <label htmlFor="spotUid" className="block text-sm font-medium text-gray-700 mb-1">车位UID <span className="text-red-500">*</span></label>
            <input 
              type="text" 
              name="spotUid" 
              id="spotUid" 
              value={newSpotData.spotUid}
              onChange={handleNewSpotDataChange}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
              required
            />
          </div>
          <div className="mb-4">
            <label htmlFor="locationDesc" className="block text-sm font-medium text-gray-700 mb-1">位置描述 (最多200字符)</label>
            <textarea 
              name="locationDesc" 
              id="locationDesc" 
              value={newSpotData.locationDesc || ''}
              onChange={handleNewSpotDataChange}
              rows={3}
              maxLength={200}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
            />
          </div>
          <div className="mb-4">
            <label htmlFor="status" className="block text-sm font-medium text-gray-700 mb-1">状态</label>
            <select 
              name="status" 
              id="status"
              value={newSpotData.status}
              onChange={handleNewSpotDataChange}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
            >
              <option value="AVAILABLE">可用</option>
              <option value="OCCUPIED">占用</option>
              <option value="MAINTENANCE">维护中</option>
              <option value="RESERVED">预留</option> 
            </select>
          </div>
          <div className="flex items-center mb-4">
            <input 
              type="checkbox" 
              name="robotAssignable" 
              id="robotAssignable" 
              checked={newSpotData.robotAssignable}
              onChange={handleNewSpotDataChange}
              className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
            />
            <label htmlFor="robotAssignable" className="ml-2 block text-sm text-gray-900">机器人可分配</label>
          </div>
        </form>
      </Modal>

      {/* Edit Spot Modal */} 
      {editingSpot && (
        <Modal
          isOpen={isEditModalOpen}
          onClose={closeEditModal}
          title={`编辑车位: ${editingSpot.spotUid}`}
          footer={
            <div className="flex justify-end space-x-2">
              <button 
                onClick={closeEditModal}
                className="px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"
              >
                取消
              </button>
              <button 
                onClick={handleUpdateSpot}
                disabled={editSpotLoading}
                className="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
              >
                {editSpotLoading ? '保存中...' : '保存更改'}
              </button>
            </div>
          }
        >
          <form onSubmit={(e) => { e.preventDefault(); handleUpdateSpot(); }}>
            {editSpotError && <p className="text-red-500 text-sm mb-3 bg-red-100 p-2 rounded">{editSpotError}</p>}
            <div className="mb-4">
              <label htmlFor="editSpotUid" className="block text-sm font-medium text-gray-700 mb-1">车位UID</label>
              <input 
                type="text" 
                name="spotUid" 
                id="editSpotUid" 
                value={editingSpot.spotUid || ''} 
                className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100 sm:text-sm"
                readOnly 
              />
            </div>
            <div className="mb-4">
              <label htmlFor="editLocationDesc" className="block text-sm font-medium text-gray-700 mb-1">位置描述 (最多200字符)</label>
              <textarea 
                name="locationDesc" 
                id="editLocationDesc" 
                value={editingSpot.locationDesc || ''}
                onChange={handleEditingSpotDataChange}
                rows={3}
                maxLength={200}
                className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
              />
            </div>
            <div className="mb-4">
              <label htmlFor="editStatus" className="block text-sm font-medium text-gray-700 mb-1">状态</label>
              <select 
                name="status" 
                id="editStatus"
                value={editingSpot.status || 'AVAILABLE'}
                onChange={handleEditingSpotDataChange}
                className="mt-1 block w-full px-3 py-2 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
              >
                <option value="AVAILABLE">可用</option>
                <option value="OCCUPIED">占用</option>
                <option value="MAINTENANCE">维护中</option>
                <option value="RESERVED">预留</option>
              </select>
            </div>
            <div className="flex items-center mb-4">
              <input 
                type="checkbox" 
                name="robotAssignable" 
                id="editRobotAssignable" 
                checked={editingSpot.robotAssignable || false}
                onChange={handleEditingSpotDataChange}
                className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <label htmlFor="editRobotAssignable" className="ml-2 block text-sm text-gray-900">机器人可分配</label>
            </div>
          </form>
        </Modal>
      )}

      {/* Delete Confirmation Modal */} 
      {deletingSpotInfo && (
        <Modal
          isOpen={isDeleteConfirmOpen}
          onClose={closeDeleteConfirm}
          title="确认删除车位"
          footer={
            <div className="flex justify-end space-x-2">
              <button 
                onClick={closeDeleteConfirm}
                className="px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"
              >
                取消
              </button>
              <button 
                onClick={handleDeleteSpot}
                disabled={deleteSpotLoading}
                className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50"
              >
                {deleteSpotLoading ? '删除中...' : '删除'}
              </button>
            </div>
          }
        >
          <p className="text-gray-700">
            您确定要删除车位 <span className="font-semibold">{deletingSpotInfo.spotUid}</span> 吗？ 
            此操作无法撤销。
          </p>
          {deleteSpotError && <p className="text-red-500 text-sm mt-3 bg-red-100 p-2 rounded">{deleteSpotError}</p>}
        </Modal>
      )}

      {loading && <LoadingSpinner />}
      {error && <p className="text-red-500 bg-red-100 p-3 rounded-md">错误: {error}</p>}
      
      {!loading && !error && (
        <>
          {/* Parking Spots Table */} 
          <div className="bg-white shadow-xl rounded-lg overflow-hidden">
            <table className="min-w-full leading-normal">
              <thead className="bg-gray-800 text-white">
                <tr>
                  <th onClick={() => handleSort('spotUid')} className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-semibold uppercase tracking-wider cursor-pointer">车位UID <SortIndicator field="spotUid" /></th>
                  <th className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-semibold uppercase tracking-wider">位置</th>
                  <th onClick={() => handleSort('status')} className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-semibold uppercase tracking-wider cursor-pointer">状态 <SortIndicator field="status" /></th>
                  <th onClick={() => handleSort('robotAssignable')} className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-semibold uppercase tracking-wider cursor-pointer">机器人可分配 <SortIndicator field="robotAssignable" /></th>
                  <th onClick={() => handleSort('updateTime')} className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-semibold uppercase tracking-wider cursor-pointer">最后更新 <SortIndicator field="updateTime" /></th>
                  <th className="px-5 py-3 border-b-2 border-gray-200 text-left text-xs font-semibold uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody className="text-gray-700">
                {parkingSpots.length > 0 ? (
                  parkingSpots.map((spot) => (
                    <tr key={spot.id} className="hover:bg-gray-100 border-b border-gray-200">
                      <td className="px-5 py-4 text-sm">{spot.spotUid}</td>
                      <td className="px-5 py-4 text-sm">{spot.locationDesc || 'N/A'}</td>
                      <td className="px-5 py-4 text-sm">
                        <span 
                          className={`px-2 py-1 font-semibold leading-tight rounded-full text-xs 
                            ${spot.status === 'AVAILABLE' ? 'bg-green-100 text-green-700' : 
                              spot.status === 'OCCUPIED' ? 'bg-yellow-100 text-yellow-700' : 
                              spot.status === 'MAINTENANCE' ? 'bg-red-100 text-red-700' : 
                              spot.status === 'RESERVED' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-700'}
                          `}
                        >
                          {spot.status === 'AVAILABLE' ? '可用' : 
                           spot.status === 'OCCUPIED' ? '占用' : 
                           spot.status === 'MAINTENANCE' ? '维护中' : 
                           spot.status === 'RESERVED' ? '预留' : spot.status}
                        </span>
                      </td>
                      <td className="px-5 py-4 text-sm">{spot.robotAssignable ? '是' : '否'}</td>
                      <td className="px-5 py-4 text-sm">{new Date(spot.updateTime).toLocaleString()}</td>
                      <td className="px-5 py-4 text-sm">
                        <button 
                          onClick={() => openEditModal(spot)} 
                          className="text-indigo-600 hover:text-indigo-900 mr-3"
                        >
                          编辑
                        </button>
                        <button 
                          onClick={() => openDeleteConfirm(spot)} 
                          className="text-red-600 hover:text-red-900"
                        >
                          删除
                        </button>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={6} className="text-center py-10 text-gray-500">
                      未找到车位信息。
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination Controls */} 
          {totalSpots > 0 && (
               <div className="py-5 flex items-center justify-between">
                    <div className="flex items-center">
                        <span className="text-xs xs:text-sm text-gray-700 mr-4">
                            显示第 {((queryParams.current || 1) - 1) * (queryParams.pageSize || 10) + 1} 到 {Math.min((queryParams.current || 1) * (queryParams.pageSize || 10), totalSpots)} 条，共 {totalSpots} 条车位记录
                        </span>
                        <select 
                            value={queryParams.pageSize}
                            onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                            className="text-xs xs:text-sm border border-gray-300 rounded-md p-1 shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                        >
                            <option value={10}>10 条/页</option>
                            <option value={20}>20 条/页</option>
                            <option value={50}>50 条/页</option>
                        </select>
                    </div>
                    <div className="inline-flex mt-2 xs:mt-0">
                        <button 
                            onClick={() => handlePageChange((queryParams.current || 1) - 1)}
                            disabled={(queryParams.current || 1) <= 1}
                            className="text-sm bg-gray-300 hover:bg-gray-400 text-gray-800 font-semibold py-2 px-4 rounded-l disabled:opacity-50"
                        >
                            上一页
                        </button>
                        <button 
                            onClick={() => handlePageChange((queryParams.current || 1) + 1)}
                            disabled={((queryParams.current || 1) * (queryParams.pageSize || 10)) >= totalSpots}
                            className="text-sm bg-gray-300 hover:bg-gray-400 text-gray-800 font-semibold py-2 px-4 rounded-r disabled:opacity-50"
                        >
                            下一页
                        </button>
                    </div>
              </div>
          )}
        </>
      )}
    </div>
  );
};

export default AdminParkingSpotsPage; 