
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { dataService } from '../services/dataService';
import { IPMSchedule, IContract, IUser, IContractType, IRole } from '../types';
import { CalendarDays, Filter, RefreshCcw, User, Plus, X, Edit, Trash2, Search, AlertTriangle, CheckCircle, Clock, ArrowUpDown, Grid3x3, List, ChevronLeft, ChevronRight, ChevronDown, ChevronUp, FileText } from 'lucide-react';
import { useUIStore } from '../store/useUIStore';
import { useAssetStore } from '../store/useAssetStore';
import { pmScheduleStatusVi } from '../utils/displayVi';

const MaintenanceSchedule: React.FC = () => {
   const { selectedProjectId } = useAssetStore();
   const [schedules, setSchedules] = useState<IPMSchedule[]>([]);
   const [contracts, setContracts] = useState<IContract[]>([]);
   const [contractTypes, setContractTypes] = useState<IContractType[]>([]);
   const [users, setUsers] = useState<IUser[]>([]);
   const [roles, setRoles] = useState<IRole[]>([]);

   const [loading, setLoading] = useState(true);
   const [generating, setGenerating] = useState(false);
   const [error, setError] = useState<string | null>(null);
   const { addNotification } = useUIStore();

   // Filter & Search State
   const [searchQuery, setSearchQuery] = useState('');
   const [statusFilter, setStatusFilter] = useState<string>('all');
   const [frequencyFilter, setFrequencyFilter] = useState<string>('all');
   const [sortField, setSortField] = useState<keyof IPMSchedule>('nextDue');
   const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
   const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');

   // Modal State
   const [isModalOpen, setIsModalOpen] = useState(false);
   const [editingSchedule, setEditingSchedule] = useState<IPMSchedule | null>(null);
   const [deletingScheduleId, setDeletingScheduleId] = useState<string | null>(null);
   const [formData, setFormData] = useState<Partial<IPMSchedule> & { assignedToIds?: string[] }>({
      title: '',
      contractId: '',
      frequency: 'Monthly',
      nextDue: new Date().toISOString().split('T')[0],
      assignedTo: '',
      assignedToIds: [],
      status: 'Active'
   });

   useEffect(() => {
      if (selectedProjectId) {
         loadData();
      }
   }, [selectedProjectId]);

   const loadData = async () => {
      if (!selectedProjectId) return;
      setLoading(true);
      setError(null);
      try {
         const [schedulesData, contractsData, typesData, usersData, rolesData] = await Promise.all([
            dataService.getPMSchedules(selectedProjectId),
            dataService.getContracts(selectedProjectId),
            dataService.getContractTypes(),
            dataService.getUserDirectory(),
            dataService.getRoles()
         ]);
         setSchedules(schedulesData);
         setContractTypes(typesData);
         setRoles(rolesData);

         // Find O&M, EPC, and PPA contract types from database (case-insensitive match on code or name)
         const omContractType = typesData.find(t =>
            t.code.toUpperCase() === 'O&M' ||
            t.code.toUpperCase() === 'OM' ||
            t.name.toUpperCase().includes('O&M') ||
            t.name.toUpperCase().includes('OM')
         );
         const epcContractType = typesData.find(t =>
            t.code.toUpperCase() === 'EPC' ||
            t.name.toUpperCase().includes('EPC')
         );
         const ppaContractType = typesData.find(t =>
            t.code.toUpperCase() === 'PPA' ||
            t.name.toUpperCase().includes('PPA')
         );

         // Filter contracts to include O&M, EPC, and PPA - exclude only invalid statuses (expired, terminated, completed)
         const filteredContracts = contractsData.filter(c => {
            // Normalize contract type for comparison (handle both "O&M" and "OM")
            const contractType = (c.contractType || '').trim();
            const contractTypeUpper = contractType.toUpperCase();
            const contractTypeNormalized = contractTypeUpper.replace(/[&-\s]/g, ''); // Remove &, spaces, dashes

            // Check if contract type matches O&M, EPC, or PPA contract type code
            let isOM = false;
            let isEPC = false;
            let isPPA = false;

            // Check O&M
            if (omContractType) {
               isOM = contractType === omContractType.code ||
                  contractTypeNormalized === omContractType.code.toUpperCase().replace(/[&-\s]/g, '');
            }
            if (!isOM) {
               isOM = contractTypeUpper === 'O&M' ||
                  contractTypeUpper === 'OM' ||
                  contractTypeNormalized === 'OM';
            }

            // Check EPC
            if (epcContractType) {
               isEPC = contractType === epcContractType.code ||
                  contractTypeNormalized === epcContractType.code.toUpperCase().replace(/[&-\s]/g, '');
            }
            if (!isEPC) {
               isEPC = contractTypeUpper === 'EPC';
            }

            // Check PPA
            if (ppaContractType) {
               isPPA = contractType === ppaContractType.code ||
                  contractTypeNormalized === ppaContractType.code.toUpperCase().replace(/[&-\s]/g, '');
            }
            if (!isPPA) {
               isPPA = contractTypeUpper === 'PPA';
            }

            const isInvalidStatus = c.status === 'expired' ||
               c.status === 'terminated' ||
               c.status === 'completed';
            return (isOM || isEPC || isPPA) && !isInvalidStatus;
         });
         setContracts(filteredContracts);
         setUsers(usersData);
      } catch (err) {
         const errorMessage = err instanceof Error ? err.message : 'Lỗi khi tải dữ liệu';
         setError(errorMessage);
         addNotification('error', errorMessage);
      } finally {
         setLoading(false);
      }
   };

   const handleAutoSchedule = async () => {
      setGenerating(true);
      try {
         const count = await dataService.runPMScheduler();
         if (count > 0) {
            addNotification('success', `Đã tạo tự động ${count} Work Order từ lịch bảo trì.`);
            await loadData();
         } else {
            addNotification('info', 'Không có lịch bảo trì nào đến hạn trong 7 ngày tới.');
         }
      } catch (err) {
         const errorMessage = err instanceof Error ? err.message : 'Lỗi khi tạo lịch tự động.';
         addNotification('error', errorMessage);
      } finally {
         setGenerating(false);
      }
   };

   const handleAdd = () => {
      setEditingSchedule(null);
      setFormData({
         projectId: selectedProjectId || '',
         title: '',
         contractId: '',
         frequency: 'Monthly',
         nextDue: new Date().toISOString().split('T')[0],
         assignedTo: '',
         assignedToIds: [],
         status: 'Active'
      });
      setIsModalOpen(true);
   };

   const handleEdit = (schedule: IPMSchedule) => {
      setEditingSchedule(schedule);
      // Handle both string and array formats for assignedTo
      let assignedToIds: string[] = [];
      if (Array.isArray(schedule.assignedTo)) {
         assignedToIds = schedule.assignedTo;
      } else if (schedule.assignedTo) {
         // If it's a string, try to parse it as comma-separated IDs or use as single ID
         const assignedToStr = schedule.assignedTo.toString();
         if (assignedToStr.includes(',')) {
            assignedToIds = assignedToStr.split(',').map(id => id.trim()).filter(id => id);
         } else {
            assignedToIds = [assignedToStr];
         }
      }
      setFormData({
         ...schedule,
         nextDue:
            typeof schedule.nextDue === 'string'
               ? schedule.nextDue.split('T')[0]
               : new Date(schedule.nextDue).toISOString().split('T')[0],
         assignedToIds: assignedToIds
      });
      setIsModalOpen(true);
   };

   const handleDeleteClick = (id: string) => {
      setDeletingScheduleId(id);
   };

   const handleDeleteConfirm = async () => {
      if (!deletingScheduleId) return;
      try {
         await dataService.deletePMSchedule(deletingScheduleId);
         addNotification('success', 'Xóa lịch thành công');
         setDeletingScheduleId(null);
         await loadData();
      } catch (err) {
         const errorMessage = err instanceof Error ? err.message : 'Lỗi khi xóa lịch';
         addNotification('error', errorMessage);
      }
   };

   const handleSubmit = async (e: React.FormEvent) => {
      e.preventDefault();
      try {
         // Convert assignedToIds array to assignedTo (comma-separated string or array)
         const assignedToValue = formData.assignedToIds && formData.assignedToIds.length > 0 
            ? formData.assignedToIds.join(',') 
            : '';
         
         // Ensure projectId is set from selectedProjectId
         const submitData = {
            ...formData,
            projectId: selectedProjectId || formData.projectId,
            assignedTo: assignedToValue
         };

         if (editingSchedule) {
            await dataService.updatePMSchedule({ ...editingSchedule, ...submitData } as IPMSchedule);
            addNotification('success', 'Cập nhật lịch thành công');
         } else {
            await dataService.createPMSchedule(submitData);
            addNotification('success', 'Tạo lịch mới thành công');
         }
         setIsModalOpen(false);
         await loadData();
      } catch (err) {
         const errorMessage = err instanceof Error ? err.message : 'Lỗi khi lưu lịch';
         addNotification('error', errorMessage);
      }
   };

   // Helper: Get role code from role name
   const getRoleCodeByName = useCallback((roleName: string): string | null => {
      const role = roles.find(r => r.name === roleName && r.isActive);
      return role?.code || null;
   }, [roles]);

   // Helper: Check if user has a specific role by code
   const userHasRoleCode = useCallback((user: IUser, roleCode: string): boolean => {
      if (!user.role) return false;
      const userRoleCode = getRoleCodeByName(user.role);
      return userRoleCode === roleCode;
   }, [getRoleCodeByName]);

   // Helper to get contract name/number
   const getContractName = useCallback((id: any) => {
      const contract = contracts.find(c => c._id === id || c._id === id?.toString());
      return contract ? `${contract.contractNumber} - ${contract.partyA}` : 'Unknown Contract';
   }, [contracts]);

   // Helper to get frequency label in Vietnamese
   const getFrequencyLabel = useCallback((frequency: string) => {
      const frequencyMap: { [key: string]: string } = {
         'Daily': 'Hàng ngày',
         'Weekly': 'Hàng tuần',
         'Monthly': 'Hàng tháng',
         'Quarterly': 'Hàng quý',
         'Semi-Annually': 'Bán niên',
         'Annually': 'Hàng năm'
      };
      return frequencyMap[frequency] || frequency;
   }, []);

   // Helper to get user name(s)
   const getUserName = useCallback((assignedTo: any) => {
      if (!assignedTo) return 'Chưa được gán';
      
      // Handle array format
      if (Array.isArray(assignedTo)) {
         if (assignedTo.length === 0) return 'Chưa được gán';
         const names = assignedTo
            .map(id => {
               if (!id || id.toString().trim() === '') return null;
               const user = users.find(u => u._id === id || u._id === id?.toString());
               return user ? user.name : null;
            })
            .filter(name => name !== null && name !== '');
         return names.length > 0 ? names.join(', ') : 'Chưa được gán';
      }
      
      // Handle comma-separated string
      if (typeof assignedTo === 'string') {
         // Clean up the string - remove extra commas and whitespace
         const cleaned = assignedTo.trim();
         if (!cleaned || cleaned === '') return 'Chưa được gán';
         
         if (cleaned.includes(',')) {
            const ids = cleaned
               .split(',')
               .map(id => id.trim())
               .filter(id => id && id !== '' && id !== ',');
            
            if (ids.length === 0) return 'Chưa được gán';
            
            const names = ids
               .map(id => {
                  const user = users.find(u => u._id === id || u._id === id?.toString());
                  return user ? user.name : null;
               })
               .filter(name => name !== null && name !== '');
            
            return names.length > 0 ? names.join(', ') : 'Chưa được gán';
         }
      }
      
      // Handle single ID or name
      const user = users.find(u => u._id === assignedTo || u._id === assignedTo?.toString());
      if (user) return user.name || 'Chưa được gán';
      
      // If not found as ID, check if it's already a name string (but not empty or just commas)
      const assignedToStr = assignedTo.toString().trim();
      if (assignedToStr && assignedToStr !== '' && assignedToStr !== ',') {
         return assignedToStr;
      }
      
      return 'Chưa được gán';
   }, [users]);

   // Memoized statistics
   const stats = useMemo(() => {
      const now = new Date();
      return {
         active: schedules.filter(s => s.status === 'Active').length,
         overdue: schedules.filter(s => {
            if (s.status !== 'Active') return false;
            return new Date(s.nextDue) < now;
         }).length,
         upcoming: schedules.filter(s => {
            if (s.status !== 'Active') return false;
            const dueDate = new Date(s.nextDue);
            const daysUntilDue = Math.ceil((dueDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
            return dueDate >= now && daysUntilDue <= 7;
         }).length,
         total: schedules.length
      };
   }, [schedules]);

   // Memoized filtered and sorted schedules
   const filteredAndSortedSchedules = useMemo(() => {
      let filtered = [...schedules];

      // Apply search filter
      if (searchQuery.trim()) {
         const query = searchQuery.toLowerCase();
         filtered = filtered.filter(schedule => {
            const contractName = getContractName(schedule.contractId).toLowerCase();
            const assignedName = getUserName(schedule.assignedTo).toLowerCase();
            return (
               schedule.title?.toLowerCase().includes(query) ||
               contractName.includes(query) ||
               assignedName.includes(query) ||
               schedule.frequency?.toLowerCase().includes(query)
            );
         });
      }

      // Apply status filter
      if (statusFilter !== 'all') {
         filtered = filtered.filter(schedule => schedule.status === statusFilter);
      }

      // Apply frequency filter
      if (frequencyFilter !== 'all') {
         filtered = filtered.filter(schedule => schedule.frequency === frequencyFilter);
      }

      // Apply sorting
      filtered.sort((a, b) => {
         let aValue: any = a[sortField];
         let bValue: any = b[sortField];

         // Handle date fields
         if (sortField === 'nextDue') {
            aValue = new Date(aValue || 0).getTime();
            bValue = new Date(bValue || 0).getTime();
         }

         // Handle string fields
         if (typeof aValue === 'string') {
            aValue = aValue.toLowerCase();
            bValue = (bValue || '').toLowerCase();
         }

         if (aValue < bValue) return sortDirection === 'asc' ? -1 : 1;
         if (aValue > bValue) return sortDirection === 'asc' ? 1 : -1;
         return 0;
      });

      return filtered;
   }, [schedules, searchQuery, statusFilter, frequencyFilter, sortField, sortDirection, getContractName, getUserName]);

   // Sort handler
   const handleSort = useCallback((field: keyof IPMSchedule) => {
      if (sortField === field) {
         setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
      } else {
         setSortField(field);
         setSortDirection('asc');
      }
   }, [sortField, sortDirection]);

   // Calendar state
   const [currentMonth, setCurrentMonth] = useState(new Date());
   const [isCalendarExpanded, setIsCalendarExpanded] = useState(false);

   // Helper function to calculate next occurrence dates for a schedule
   const getScheduleDates = useCallback((schedule: IPMSchedule, monthsToShow: number = 3): Date[] => {
      if (schedule.status !== 'Active') return [];

      const dates: Date[] = [];
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      const startDate = new Date(schedule.nextDue);
      startDate.setHours(0, 0, 0, 0);

      // Calculate end date (monthsToShow months from now)
      const endDate = new Date();
      endDate.setMonth(endDate.getMonth() + monthsToShow);
      endDate.setHours(23, 59, 59, 999);

      // Always include the nextDue date if it's within the visible range
      // This shows overdue schedules
      const visibleStartDate = new Date();
      visibleStartDate.setMonth(visibleStartDate.getMonth() - 1); // Show 1 month back for overdue items
      visibleStartDate.setHours(0, 0, 0, 0);

      let currentDate = new Date(startDate);

      // If nextDue is in the past, start from nextDue and generate forward
      // If nextDue is in the future, start from nextDue
      // Always show at least the nextDue date if it's within visible range
      if (currentDate >= visibleStartDate && currentDate <= endDate) {
         dates.push(new Date(currentDate));
      }

      // Now generate future occurrences
      // Move to next occurrence if we're starting from a past date
      if (currentDate < today) {
         // Advance to next occurrence
         if (schedule.frequency === 'Daily') {
            currentDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000);
         } else if (schedule.frequency === 'Weekly') {
            currentDate = new Date(currentDate.getTime() + 7 * 24 * 60 * 60 * 1000);
         } else if (schedule.frequency === 'Monthly') {
            currentDate.setMonth(currentDate.getMonth() + 1);
         } else if (schedule.frequency === 'Quarterly') {
            currentDate.setMonth(currentDate.getMonth() + 3);
         } else if (schedule.frequency === 'Semi-Annually') {
            currentDate.setMonth(currentDate.getMonth() + 6);
         } else if (schedule.frequency === 'Annually') {
            currentDate.setFullYear(currentDate.getFullYear() + 1);
         }
      } else {
         // If nextDue is in the future, advance to the next occurrence after it
         if (schedule.frequency === 'Daily') {
            currentDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000);
         } else if (schedule.frequency === 'Weekly') {
            currentDate = new Date(currentDate.getTime() + 7 * 24 * 60 * 60 * 1000);
         } else if (schedule.frequency === 'Monthly') {
            currentDate.setMonth(currentDate.getMonth() + 1);
         } else if (schedule.frequency === 'Quarterly') {
            currentDate.setMonth(currentDate.getMonth() + 3);
         } else if (schedule.frequency === 'Semi-Annually') {
            currentDate.setMonth(currentDate.getMonth() + 6);
         } else if (schedule.frequency === 'Annually') {
            currentDate.setFullYear(currentDate.getFullYear() + 1);
         }
      }

      // Generate dates up to the end date
      while (currentDate <= endDate) {
         currentDate.setHours(0, 0, 0, 0);
         dates.push(new Date(currentDate));

         if (schedule.frequency === 'Daily') {
            currentDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000);
         } else if (schedule.frequency === 'Weekly') {
            currentDate = new Date(currentDate.getTime() + 7 * 24 * 60 * 60 * 1000);
         } else if (schedule.frequency === 'Monthly') {
            currentDate.setMonth(currentDate.getMonth() + 1);
         } else if (schedule.frequency === 'Quarterly') {
            currentDate.setMonth(currentDate.getMonth() + 3);
         } else if (schedule.frequency === 'Semi-Annually') {
            currentDate.setMonth(currentDate.getMonth() + 6);
         } else if (schedule.frequency === 'Annually') {
            currentDate.setFullYear(currentDate.getFullYear() + 1);
         }
      }

      return dates;
   }, []);

   // Get all dates with schedules
   const scheduleDatesMap = useMemo(() => {
      const map = new Map<string, IPMSchedule[]>();
      const monthsToShow = 3; // Show 3 months ahead

      schedules.forEach(schedule => {
         const dates = getScheduleDates(schedule, monthsToShow);
         dates.forEach(date => {
            const dateKey = date.toISOString().split('T')[0];
            if (!map.has(dateKey)) {
               map.set(dateKey, []);
            }
            map.get(dateKey)!.push(schedule);
         });
      });

      return map;
   }, [schedules, getScheduleDates]);

   // Calendar helper functions
   const getDaysInMonth = (date: Date) => {
      const year = date.getFullYear();
      const month = date.getMonth();
      const firstDay = new Date(year, month, 1);
      const lastDay = new Date(year, month + 1, 0);
      const daysInMonth = lastDay.getDate();
      const startingDayOfWeek = firstDay.getDay();

      const days: (Date | null)[] = [];

      // Add empty cells for days before the first day of the month
      for (let i = 0; i < startingDayOfWeek; i++) {
         days.push(null);
      }

      // Add all days of the month
      for (let day = 1; day <= daysInMonth; day++) {
         days.push(new Date(year, month, day));
      }

      return days;
   };

   const formatMonthYear = (date: Date) => {
      return date.toLocaleDateString('vi-VN', { month: 'long', year: 'numeric' });
   };

   const isToday = (date: Date | null) => {
      if (!date) return false;
      const today = new Date();
      return date.getDate() === today.getDate() &&
         date.getMonth() === today.getMonth() &&
         date.getFullYear() === today.getFullYear();
   };

   const isPast = (date: Date | null) => {
      if (!date) return false;
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const checkDate = new Date(date);
      checkDate.setHours(0, 0, 0, 0);
      return checkDate < today;
   };

   const getDateKey = (date: Date | null) => {
      if (!date) return '';
      return date.toISOString().split('T')[0];
   };

   const navigateMonth = (direction: 'prev' | 'next') => {
      setCurrentMonth(prev => {
         const newDate = new Date(prev);
         if (direction === 'prev') {
            newDate.setMonth(newDate.getMonth() - 1);
         } else {
            newDate.setMonth(newDate.getMonth() + 1);
         }
         return newDate;
      });
   };

   // Render calendar month
   const renderCalendarMonth = (monthDate: Date) => {
      const days = getDaysInMonth(monthDate);
      const weekDays = ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'];

      return (
         <div className="bg-white dark:bg-slate-800 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700 p-4">
            <div className="text-center font-bold text-lg text-slate-800 dark:text-white mb-4">
               {formatMonthYear(monthDate)}
            </div>
            <div className="grid grid-cols-7 gap-1">
               {weekDays.map(day => (
                  <div key={day} className="text-center text-xs font-semibold text-slate-500 dark:text-slate-400 py-2">
                     {day}
                  </div>
               ))}
               {days.map((date, index) => {
                  if (!date) {
                     return <div key={`empty-${index}`} className="aspect-square" />;
                  }

                  const dateKey = getDateKey(date);
                  const daySchedules = scheduleDatesMap.get(dateKey) || [];
                  const hasSchedule = daySchedules.length > 0;
                  const isTodayDate = isToday(date);
                  const isPastDate = isPast(date);

                  return (
                     <div
                        key={dateKey}
                        className={`aspect-square flex flex-col items-center justify-center rounded-lg text-sm relative ${isTodayDate
                              ? 'bg-blue-100 dark:bg-blue-900/30 border-2 border-blue-500 font-bold'
                              : isPastDate
                                 ? 'text-slate-400 dark:text-slate-500'
                                 : 'text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700'
                           }`}
                        title={hasSchedule ? `${daySchedules.length} lịch bảo trì` : ''}
                     >
                        <span>{date.getDate()}</span>
                        {hasSchedule && (
                           <div className="absolute bottom-1 left-1/2 transform -translate-x-1/2 flex gap-0.5">
                              {daySchedules.map((schedule, idx) => {
                                 const isOverdue = new Date(schedule.nextDue) < new Date() &&
                                    date.toDateString() === new Date(schedule.nextDue).toDateString();
                                 return (
                                    <div
                                       key={idx}
                                       className={`w-1.5 h-1.5 rounded-full ${isOverdue
                                             ? 'bg-red-500'
                                             : isTodayDate
                                                ? 'bg-blue-600'
                                                : 'bg-green-500'
                                          }`}
                                    />
                                 );
                              })}
                           </div>
                        )}
                     </div>
                  );
               })}
            </div>
         </div>
      );
   };

   if (loading) {
      return (
         <div className="flex items-center justify-center h-64">
            <div className="text-slate-500 dark:text-slate-400">Đang tải dữ liệu...</div>
         </div>
      );
   }

   if (error) {
      return (
         <div className="flex items-center justify-center h-64">
            <div className="text-red-500 dark:text-red-400">Lỗi: {error}</div>
         </div>
      );
   }

   return (
      <div className="space-y-6">
         <div className="flex justify-between items-center">
            <div>
               <h1 className="text-2xl font-bold text-slate-800 dark:text-white">Lịch Bảo trì (PM Schedule)</h1>
               <p className="text-sm text-slate-500 dark:text-slate-400">Quản lý kế hoạch bảo trì định kỳ theo hợp đồng O&M.</p>
            </div>
            <div className="flex gap-2">
               <button
                  onClick={handleAdd}
                  className="flex items-center gap-2 bg-green-600 text-white px-4 py-2 rounded-lg text-sm hover:bg-green-700"
               >
                  <Plus size={16} /> Thêm lịch
               </button>
               <button
                  onClick={handleAutoSchedule}
                  disabled={generating}
                  className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-700 disabled:opacity-70"
               >
                  <RefreshCcw size={16} className={generating ? "animate-spin" : ""} />
                  {generating ? 'Đang xử lý...' : 'Tạo Work Order tự động'}
               </button>
            </div>
         </div>

         {/* Statistics */}
         <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700 flex items-center justify-between">
               <div>
                  <p className="text-slate-500 dark:text-slate-400 text-sm">Tổng số lịch</p>
                  <p className="text-2xl font-bold text-slate-800 dark:text-white">{stats.total}</p>
               </div>
               <CalendarDays className="text-blue-500" />
            </div>
            <div className="bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700 flex items-center justify-between">
               <div>
                  <p className="text-slate-500 dark:text-slate-400 text-sm">Đang hoạt động</p>
                  <p className="text-2xl font-bold text-slate-800 dark:text-white">{stats.active}</p>
               </div>
               <CheckCircle className="text-green-500" />
            </div>
            <div className="bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700 flex items-center justify-between">
               <div>
                  <p className="text-slate-500 dark:text-slate-400 text-sm">Quá hạn</p>
                  <p className="text-2xl font-bold text-red-600 dark:text-red-400">{stats.overdue}</p>
               </div>
               <AlertTriangle className="text-red-500" />
            </div>
            <div className="bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700 flex items-center justify-between">
               <div>
                  <p className="text-slate-500 dark:text-slate-400 text-sm">Sắp đến hạn (7 ngày)</p>
                  <p className="text-2xl font-bold text-slate-800 dark:text-white">{stats.upcoming}</p>
               </div>
               <Clock className="text-yellow-500" />
            </div>
         </div>

         {/* Calendar View */}
         <div className={`bg-white dark:bg-slate-800 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700 transition-all ${isCalendarExpanded ? 'p-4' : 'p-3'}`}>
            <div className={`flex items-center justify-between ${isCalendarExpanded ? 'mb-4' : ''}`}>
               <button
                  onClick={() => setIsCalendarExpanded(!isCalendarExpanded)}
                  className={`flex items-center gap-2 text-slate-700 dark:text-slate-300 hover:text-slate-900 dark:hover:text-white transition-colors ${isCalendarExpanded
                        ? 'text-base font-semibold'
                        : 'text-sm font-medium'
                     }`}
               >
                  <CalendarDays size={isCalendarExpanded ? 18 : 16} className="text-slate-500 dark:text-slate-400" />
                  <span>Lịch bảo trì</span>
                  {isCalendarExpanded ? (
                     <ChevronUp size={16} className="text-slate-400 dark:text-slate-500" />
                  ) : (
                     <ChevronDown size={16} className="text-slate-400 dark:text-slate-500" />
                  )}
               </button>
               {isCalendarExpanded && (
                  <div className="flex items-center gap-2">
                     <button
                        onClick={() => navigateMonth('prev')}
                        className="p-1 rounded hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-600 dark:text-slate-400"
                        title="Tháng trước"
                     >
                        <ChevronLeft size={20} />
                     </button>
                     <button
                        onClick={() => setCurrentMonth(new Date())}
                        className="px-3 py-1 text-sm rounded hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-600 dark:text-slate-400"
                        title="Hôm nay"
                     >
                        Hôm nay
                     </button>
                     <button
                        onClick={() => navigateMonth('next')}
                        className="p-1 rounded hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-600 dark:text-slate-400"
                        title="Tháng sau"
                     >
                        <ChevronRight size={20} />
                     </button>
                  </div>
               )}
            </div>

            {isCalendarExpanded && (
               <>
                  <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                     {(() => {
                        // Show current month and next 2 months on desktop, only current month on mobile
                        const month1 = new Date(currentMonth);
                        const month2 = new Date(currentMonth);
                        month2.setMonth(month2.getMonth() + 1);
                        const month3 = new Date(currentMonth);
                        month3.setMonth(month3.getMonth() + 2);

                        return (
                           <>
                              <div>
                                 {renderCalendarMonth(month1)}
                              </div>
                              <div className="hidden lg:block">
                                 {renderCalendarMonth(month2)}
                              </div>
                              <div className="hidden lg:block">
                                 {renderCalendarMonth(month3)}
                              </div>
                           </>
                        );
                     })()}
                  </div>

                  <div className="mt-4 flex flex-wrap gap-4 text-xs text-slate-500 dark:text-slate-400">
                     <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full bg-blue-100 dark:bg-blue-900/30 border-2 border-blue-500"></div>
                        <span>Hôm nay</span>
                     </div>
                     <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full bg-green-500"></div>
                        <span>Có lịch bảo trì</span>
                     </div>
                     <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full bg-red-500"></div>
                        <span>Quá hạn</span>
                     </div>
                  </div>
               </>
            )}
         </div>

         {/* Filters and Search */}
         <div className="bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700">
            <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
               <div className="flex-1 w-full md:w-auto">
                  <div className="relative">
                     <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 text-slate-400" size={16} />
                     <input
                        type="text"
                        placeholder="Tìm kiếm lịch bảo trì..."
                        className="w-full pl-8 pr-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg text-sm bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                     />
                  </div>
               </div>
               <div className="flex gap-2 flex-wrap">
                  <select
                     className="border border-slate-300 dark:border-slate-600 rounded-lg text-sm p-2 bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                     value={statusFilter}
                     onChange={(e) => setStatusFilter(e.target.value)}
                  >
                     <option value="all">Tất cả trạng thái</option>
                     <option value="Active">Đang hoạt động</option>
                     <option value="Inactive">Không hoạt động</option>
                  </select>
                  <select
                     className="border border-slate-300 dark:border-slate-600 rounded-lg text-sm p-2 bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                     value={frequencyFilter}
                     onChange={(e) => setFrequencyFilter(e.target.value)}
                  >
                     <option value="all">Tất cả tần suất</option>
                     <option value="Daily">Hàng ngày</option>
                     <option value="Weekly">Hàng tuần</option>
                     <option value="Monthly">Hàng tháng</option>
                     <option value="Quarterly">Hàng quý</option>
                     <option value="Semi-Annually">Bán niên</option>
                     <option value="Annually">Hàng năm</option>
                  </select>
                  <select
                     className="border border-slate-300 dark:border-slate-600 rounded-lg text-sm p-2 bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                     value={`${sortField}-${sortDirection}`}
                     onChange={(e) => {
                        const [field, direction] = e.target.value.split('-');
                        setSortField(field as keyof IPMSchedule);
                        setSortDirection(direction as 'asc' | 'desc');
                     }}
                  >
                     <option value="nextDue-asc">Sắp xếp: Ngày đến hạn (Tăng dần)</option>
                     <option value="nextDue-desc">Sắp xếp: Ngày đến hạn (Giảm dần)</option>
                     <option value="title-asc">Sắp xếp: Tiêu đề (A-Z)</option>
                     <option value="title-desc">Sắp xếp: Tiêu đề (Z-A)</option>
                     <option value="frequency-asc">Sắp xếp: Tần suất (A-Z)</option>
                     <option value="frequency-desc">Sắp xếp: Tần suất (Z-A)</option>
                  </select>
                  <div className="flex border border-slate-300 dark:border-slate-600 rounded-lg overflow-hidden">
                     <button
                        onClick={() => setViewMode('grid')}
                        className={`p-2 ${viewMode === 'grid' ? 'bg-blue-600 text-white' : 'bg-white dark:bg-slate-700 text-slate-600 dark:text-slate-300'}`}
                        title="Xem dạng lưới"
                     >
                        <Grid3x3 size={16} />
                     </button>
                     <button
                        onClick={() => setViewMode('list')}
                        className={`p-2 ${viewMode === 'list' ? 'bg-blue-600 text-white' : 'bg-white dark:bg-slate-700 text-slate-600 dark:text-slate-300'}`}
                        title="Xem dạng danh sách"
                     >
                        <List size={16} />
                     </button>
                  </div>
               </div>
            </div>
            {searchQuery && (
               <div className="mt-2 text-sm text-slate-500 dark:text-slate-400">
                  Tìm thấy {filteredAndSortedSchedules.length} lịch bảo trì
               </div>
            )}
         </div>

         {/* Schedule Grid/List */}
         {viewMode === 'grid' ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
               {filteredAndSortedSchedules.map(sch => (
                  <div key={sch._id} className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl p-5 shadow-sm hover:shadow-md transition-all relative group">
                     <div className="absolute top-4 right-4 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button onClick={() => handleEdit(sch)} className="p-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded"><Edit size={16} /></button>
                        <button onClick={() => handleDeleteClick(sch._id)} className="p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded"><Trash2 size={16} /></button>
                     </div>

                     <div className="mb-4">
                        <span className={`inline-block px-2 py-1 rounded text-xs font-semibold ${sch.status === 'Active' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-300'
                           }`}>
                           {getFrequencyLabel(sch.frequency || '')}
                        </span>
                     </div>

                     <h3 className="font-bold text-lg text-slate-800 dark:text-white mb-2">{sch.title}</h3>
                     <div className="space-y-2 text-sm text-slate-600 dark:text-slate-400">
                        <div className="flex items-center gap-2">
                           <FileText size={14} />
                           <span>Hợp đồng: {getContractName(sch.contractId)}</span>
                        </div>
                        <div className="flex items-center gap-2">
                           <CalendarDays size={14} />
                           <span>Tới hạn: <span className={new Date(sch.nextDue) < new Date() ? "text-red-500 font-bold" : ""}>
                              {new Date(sch.nextDue).toLocaleDateString('vi-VN')}
                           </span></span>
                        </div>
                        <div className="flex items-center gap-2">
                           <User size={14} />
                           <span>Phụ trách: {getUserName(sch.assignedTo)}</span>
                        </div>
                     </div>
                  </div>
               ))}
               {filteredAndSortedSchedules.length === 0 && (
                  <div className="col-span-full py-12 text-center text-slate-500 bg-white dark:bg-slate-800 rounded-xl border border-dashed border-slate-300">
                     {searchQuery || statusFilter !== 'all' || frequencyFilter !== 'all'
                        ? 'Không tìm thấy lịch bảo trì nào phù hợp với bộ lọc.'
                        : 'Chưa có lịch bảo trì nào. Nhấn "Thêm lịch" để bắt đầu.'}
                  </div>
               )}
            </div>
         ) : (
            <div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
               <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-slate-200 dark:divide-slate-700">
                     <thead className="bg-slate-50 dark:bg-slate-700/50">
                        <tr>
                           <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                              <button onClick={() => handleSort('title')} className="flex items-center gap-1 hover:text-slate-700 dark:hover:text-slate-200">
                                 Tiêu đề <ArrowUpDown size={12} />
                              </button>
                           </th>
                           <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Hợp đồng O&M</th>
                           <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                              <button onClick={() => handleSort('frequency')} className="flex items-center gap-1 hover:text-slate-700 dark:hover:text-slate-200">
                                 Tần suất <ArrowUpDown size={12} />
                              </button>
                           </th>
                           <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                              <button onClick={() => handleSort('nextDue')} className="flex items-center gap-1 hover:text-slate-700 dark:hover:text-slate-200">
                                 Ngày đến hạn <ArrowUpDown size={12} />
                              </button>
                           </th>
                           <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Phụ trách</th>
                           <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Trạng thái</th>
                           <th className="px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Thao tác</th>
                        </tr>
                     </thead>
                     <tbody className="bg-white dark:bg-slate-800 divide-y divide-slate-200 dark:divide-slate-700">
                        {filteredAndSortedSchedules.map(sch => (
                           <tr key={sch._id} className="hover:bg-slate-50 dark:hover:bg-slate-700/50">
                              <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-slate-900 dark:text-white">{sch.title}</td>
                              <td className="px-6 py-4 whitespace-nowrap text-sm text-slate-600 dark:text-slate-300">{getContractName(sch.contractId)}</td>
                              <td className="px-6 py-4 whitespace-nowrap text-sm text-slate-600 dark:text-slate-300">{getFrequencyLabel(sch.frequency || '')}</td>
                              <td className="px-6 py-4 whitespace-nowrap text-sm text-slate-600 dark:text-slate-300">
                                 <span className={new Date(sch.nextDue) < new Date() ? "text-red-500 font-bold" : ""}>
                                    {new Date(sch.nextDue).toLocaleDateString('vi-VN')}
                                 </span>
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap text-sm text-slate-600 dark:text-slate-300">{getUserName(sch.assignedTo)}</td>
                              <td className="px-6 py-4 whitespace-nowrap">
                                 <span className={`px-2 py-1 rounded text-xs font-semibold ${sch.status === 'Active' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-300'}`}>
                                    {pmScheduleStatusVi(sch.status)}
                                 </span>
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                 <div className="flex justify-end space-x-2">
                                    <button
                                       onClick={() => handleEdit(sch)}
                                       className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 p-1 rounded hover:bg-blue-50 dark:hover:bg-slate-700"
                                       title="Chỉnh sửa"
                                    >
                                       <Edit size={16} />
                                    </button>
                                    <button
                                       onClick={() => handleDeleteClick(sch._id)}
                                       className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 p-1 rounded hover:bg-red-50 dark:hover:bg-slate-700"
                                       title="Xóa"
                                    >
                                       <Trash2 size={16} />
                                    </button>
                                 </div>
                              </td>
                           </tr>
                        ))}
                        {filteredAndSortedSchedules.length === 0 && (
                           <tr>
                              <td colSpan={7} className="px-6 py-10 text-center text-slate-500 dark:text-slate-400">
                                 {searchQuery || statusFilter !== 'all' || frequencyFilter !== 'all'
                                    ? 'Không tìm thấy lịch bảo trì nào phù hợp với bộ lọc.'
                                    : 'Chưa có lịch bảo trì nào. Nhấn "Thêm lịch" để bắt đầu.'}
                              </td>
                           </tr>
                        )}
                     </tbody>
                  </table>
               </div>
            </div>
         )}

         {/* Modal */}
         {isModalOpen && (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
               <div className="bg-white dark:bg-slate-900 w-full max-w-lg rounded-xl shadow-2xl overflow-hidden">
                  <div className="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex justify-between items-center">
                     <h2 className="text-xl font-bold dark:text-white">{editingSchedule ? 'Sửa Lịch Bảo Trì' : 'Thêm Lịch Mới'}</h2>
                     <button onClick={() => setIsModalOpen(false)} className="text-slate-400 hover:text-slate-600"><X size={20} /></button>
                  </div>
                  <form onSubmit={handleSubmit} className="p-6 space-y-4">
                     <div>
                        <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Tiêu đề công việc</label>
                        <input
                           type="text"
                           required
                           className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-slate-800 dark:border-slate-700 dark:text-white"
                           value={formData.title}
                           onChange={e => setFormData({ ...formData, title: e.target.value })}
                        />
                     </div>
                     <div>
                        <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Hợp đồng O&M <span className="text-red-500">*</span></label>
                        <select
                           required
                           className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-slate-800 dark:border-slate-700 dark:text-white"
                           value={formData.contractId}
                           onChange={e => setFormData({ ...formData, contractId: e.target.value })}
                        >
                           <option value="">-- Chọn hợp đồng (O&M/EPC/PPA) --</option>
                           {contracts.map(c => (
                              <option key={c._id} value={c._id}>
                                 {c.contractNumber} - {c.partyA} {c.capacityKWp ? `(${c.capacityKWp} kWp)` : ''}
                              </option>
                           ))}
                        </select>
                        {contracts.length === 0 && (
                           <p className="text-xs text-amber-600 dark:text-amber-400 mt-1">
                              Chưa có hợp đồng O&M/EPC/PPA nào. Vui lòng tạo hợp đồng trước.
                           </p>
                        )}
                     </div>
                     <div className="grid grid-cols-2 gap-4">
                        <div>
                           <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Tần suất</label>
                           <select
                              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-slate-800 dark:border-slate-700 dark:text-white"
                              value={formData.frequency}
                              onChange={e => setFormData({ ...formData, frequency: e.target.value as any })}
                           >
                              <option value="Daily">Hàng ngày</option>
                              <option value="Weekly">Hàng tuần</option>
                              <option value="Monthly">Hàng tháng</option>
                              <option value="Quarterly">Hàng quý</option>
                              <option value="Semi-Annually">Bán niên</option>
                              <option value="Annually">Hàng năm</option>
                           </select>
                        </div>
                        <div>
                           <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Ngày đến hạn tới</label>
                           <input
                              type="date"
                              required
                              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-slate-800 dark:border-slate-700 dark:text-white"
                              value={formData.nextDue ? new Date(formData.nextDue).toISOString().split('T')[0] : ''}
                              onChange={e => setFormData({ ...formData, nextDue: e.target.value })}
                           />
                        </div>
                     </div>
                     <div>
                        <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Phân công cho</label>
                        <div className="w-full border border-slate-300 dark:border-slate-600 rounded-lg p-1.5 min-h-[48px] bg-white dark:bg-slate-800 focus-within:ring-2 focus-within:ring-blue-500">
                           {/* Selected Users as Tags */}
                           {formData.assignedToIds && formData.assignedToIds.length > 0 && (
                              <div className="flex flex-wrap gap-1.5 mb-1.5">
                                 {formData.assignedToIds.map(userId => {
                                    const user = users.find(u => u._id === userId);
                                    if (!user) return null;
                                    return (
                                       <span
                                          key={userId}
                                          className="inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded text-xs"
                                       >
                                          {user.name}
                                          <button
                                             type="button"
                                             onClick={() => {
                                                setFormData({
                                                   ...formData,
                                                   assignedToIds: formData.assignedToIds?.filter(id => id !== userId) || []
                                                });
                                             }}
                                             className="hover:bg-blue-200 dark:hover:bg-blue-900/50 rounded-full p-0.5 transition-colors"
                                          >
                                             <X size={12} />
                                          </button>
                                       </span>
                                    );
                                 })}
                              </div>
                           )}
                           {/* Dropdown to select users */}
                           <select
                              className="w-full px-1.5 py-0.5 border-0 bg-transparent text-slate-900 dark:text-white focus:outline-none focus:ring-0 text-sm [&>option]:bg-white [&>option]:dark:bg-slate-800 [&>option]:text-slate-900 [&>option]:dark:text-white"
                              value=""
                              onChange={e => {
                                 const selectedId = e.target.value;
                                 if (selectedId && !formData.assignedToIds?.includes(selectedId)) {
                                    setFormData({
                                       ...formData,
                                       assignedToIds: [...(formData.assignedToIds || []), selectedId]
                                    });
                                 }
                                 e.target.value = '';
                              }}
                           >
                              <option value="">-- Chọn người dùng --</option>
                              {users
                                 .filter(u => {
                                    const isActive = u.status === 'Active' || u.active === true;
                                    if (!isActive) return false;
                                    return userHasRoleCode(u, 'TECHNICIAN') || userHasRoleCode(u, 'OM_MANAGER');
                                 })
                                 .filter(u => !formData.assignedToIds?.includes(u._id))
                                 .map(user => (
                                    <option key={user._id} value={user._id} className="bg-white dark:bg-slate-800 text-slate-900 dark:text-white">
                                       {user.name} {user.role ? `(${user.role})` : ''}
                                    </option>
                                 ))}
                           </select>
                        </div>
                        {formData.assignedToIds && formData.assignedToIds.length === 0 && (
                           <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">
                              Chọn người dùng từ danh sách (chỉ hiển thị O&M Manager và Technician)
                           </p>
                        )}
                     </div>
                     <div className="flex justify-end gap-3 pt-4">
                        <button
                           type="button"
                           onClick={() => setIsModalOpen(false)}
                           className="px-4 py-2 text-slate-700 hover:bg-slate-100 rounded-lg dark:text-slate-300 dark:hover:bg-slate-800"
                        >
                           Hủy
                        </button>
                        <button
                           type="submit"
                           className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 shadow-sm"
                        >
                           {editingSchedule ? 'Cập nhật' : 'Thêm mới'}
                        </button>
                     </div>
                  </form>
               </div>
            </div>
         )}

         {/* Delete Confirmation Modal */}
         {deletingScheduleId && (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
               <div className="bg-white dark:bg-slate-900 w-full max-w-md rounded-xl shadow-2xl overflow-hidden">
                  <div className="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex justify-between items-center">
                     <h2 className="text-xl font-bold dark:text-white">Xác nhận xóa</h2>
                     <button onClick={() => setDeletingScheduleId(null)} className="text-slate-400 hover:text-slate-600"><X size={20} /></button>
                  </div>
                  <div className="p-6">
                     <div className="flex items-center space-x-3 mb-4">
                        <div className="flex-shrink-0 bg-red-100 dark:bg-red-900/30 rounded-full p-2">
                           <AlertTriangle className="h-6 w-6 text-red-600 dark:text-red-400" />
                        </div>
                        <div>
                           <p className="text-sm text-slate-700 dark:text-slate-300">
                              Bạn có chắc chắn muốn xóa lịch bảo trì này không? Hành động này không thể hoàn tác.
                           </p>
                        </div>
                     </div>
                     <div className="flex justify-end gap-3">
                        <button
                           onClick={() => setDeletingScheduleId(null)}
                           className="px-4 py-2 text-slate-700 hover:bg-slate-100 rounded-lg dark:text-slate-300 dark:hover:bg-slate-800"
                        >
                           Hủy
                        </button>
                        <button
                           onClick={handleDeleteConfirm}
                           className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 shadow-sm"
                        >
                           Xóa
                        </button>
                     </div>
                  </div>
               </div>
            </div>
         )}
      </div>
   );
};

export default MaintenanceSchedule;
