import React, { useEffect, useState } from 'react';
import { Search, Plus, Edit, Wrench, AlertTriangle, CheckCircle, Clock, X } from 'lucide-react';
import advancedRoomService, { MaintenanceRecord } from '../../features/rooms/services/advancedRoomService';
import roomService, { Room } from '../../features/rooms/services/roomService';
import userService, { User } from '../../features/auth/services/userService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import Pagination from '../../shared/components/Pagination';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

const MaintenanceManagementPage: React.FC = () => {
  const { formatCurrency: _formatCurrency } = useFormatCurrency();
  const [records, setRecords] = useState<MaintenanceRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingRecord, setEditingRecord] = useState<MaintenanceRecord | null>(null);
  const [rooms, setRooms] = useState<Room[]>([]);
  const [staffMembers, setStaffMembers] = useState<User[]>([]);
  const [_loadingRooms, setLoadingRooms] = useState(false);
  const [_loadingStaff, setLoadingStaff] = useState(false);
  
  const [filters, setFilters] = useState({
    search: '',
    status: '',
    maintenance_type: '',
    room_id: '',
    priority: '',
  });
  
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 20;

  const [formData, setFormData] = useState({
    room_id: 0,
    maintenance_type: 'preventive',
    title: '',
    description: '',
    scheduled_start: new Date(),
    scheduled_end: null as Date | null,
    assigned_to: 0,
    priority: 'medium',
    estimated_cost: 0,
    blocks_room: true,
    block_start: null as Date | null,
    block_end: null as Date | null,
    notes: '',
  });

  const maintenanceTypes = [
    { value: 'preventive', label: 'Preventive', color: 'bg-blue-100 text-blue-800' },
    { value: 'corrective', label: 'Corrective', color: 'bg-orange-100 text-orange-800' },
    { value: 'emergency', label: 'Emergency', color: 'bg-red-100 text-red-800' },
    { value: 'upgrade', label: 'Upgrade', color: 'bg-purple-100 text-purple-800' },
    { value: 'inspection', label: 'Inspection', color: 'bg-green-100 text-green-800' },
  ];

  const statuses = [
    { value: 'scheduled', label: 'Scheduled', color: 'bg-yellow-100 text-yellow-800' },
    { value: 'in_progress', label: 'In Progress', color: 'bg-blue-100 text-blue-800' },
    { value: 'completed', label: 'Completed', color: 'bg-green-100 text-green-800' },
    { value: 'cancelled', label: 'Cancelled', color: 'bg-gray-100 text-gray-800' },
    { value: 'on_hold', label: 'On Hold', color: 'bg-orange-100 text-orange-800' },
  ];

  const priorities = [
    { value: 'low', label: 'Low', color: 'bg-gray-100 text-gray-800' },
    { value: 'medium', label: 'Medium', color: 'bg-yellow-100 text-yellow-800' },
    { value: 'high', label: 'High', color: 'bg-orange-100 text-orange-800' },
    { value: 'urgent', label: 'Urgent', color: 'bg-red-100 text-red-800' },
  ];

  useEffect(() => {
    setCurrentPage(1);
  }, [filters]);

  useEffect(() => {
    fetchRecords();
    fetchRooms();
    fetchStaffMembers();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, currentPage]);

  const fetchRecords = async () => {
    try {
      setLoading(true);
      const params: { page: number; limit: number; room_id?: number; status?: string } = {
        page: currentPage,
        limit: itemsPerPage,
      };
      
      if (filters.status) params.status = filters.status;
      if (filters.maintenance_type) params.maintenance_type = filters.maintenance_type;
      if (filters.room_id) params.room_id = parseInt(filters.room_id);
      if (filters.priority) params.priority = filters.priority;

      const response = await advancedRoomService.getMaintenanceRecords(params);
      
      if (response.status === 'success' && response.data) {
        let recordList = response.data.maintenance_records || [];
        
        if (filters.search) {
          recordList = recordList.filter((record: MaintenanceRecord) =>
            record.title.toLowerCase().includes(filters.search.toLowerCase()) ||
            record.description?.toLowerCase().includes(filters.search.toLowerCase()) ||
            record.room_number?.toLowerCase().includes(filters.search.toLowerCase())
          );
        }
        
        setRecords(recordList);
        setTotalPages(response.data.pagination?.total_pages || 1);
        setTotalItems(response.data.pagination?.total || 0);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load maintenance records');
    } finally {
      setLoading(false);
    }
  };

  const fetchRooms = async () => {
    try {
      setLoadingRooms(true);
      const response = await roomService.getRooms({ limit: 1000 });
      if (response.data && response.data.rooms) {
        setRooms(response.data.rooms);
      }
    } catch (error) {
      console.error('Error fetching rooms:', error);
    } finally {
      setLoadingRooms(false);
    }
  };

  const fetchStaffMembers = async () => {
    try {
      setLoadingStaff(true);
      const response = await userService.getUsers({ role: 'staff', limit: 100 });
      if (response.data && response.data.users) {
        setStaffMembers(response.data.users);
      }
    } catch (error) {
      console.error('Error fetching staff members:', error);
    } finally {
      setLoadingStaff(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.room_id) {
      toast.error('Please select a room');
      return;
    }

    if (!formData.title.trim()) {
      toast.error('Please enter a title');
      return;
    }
    
    try {
      const dataToSubmit: Record<string, unknown> = {
        room_id: formData.room_id,
        maintenance_type: formData.maintenance_type,
        title: formData.title,
        description: formData.description || undefined,
        scheduled_start: formData.scheduled_start.toISOString(),
        priority: formData.priority,
        blocks_room: formData.blocks_room,
        notes: formData.notes || undefined,
      };

      if (formData.scheduled_end) {
        dataToSubmit.scheduled_end = formData.scheduled_end.toISOString();
      }

      if (formData.assigned_to) {
        dataToSubmit.assigned_to = formData.assigned_to;
      }

      if (formData.estimated_cost > 0) {
        dataToSubmit.estimated_cost = formData.estimated_cost;
      }

      if (formData.blocks_room) {
        if (formData.block_start) {
          dataToSubmit.block_start = formData.block_start.toISOString();
        }
        if (formData.block_end) {
          dataToSubmit.block_end = formData.block_end.toISOString();
        }
      }

      if (editingRecord) {
        await advancedRoomService.updateMaintenanceRecord(editingRecord.id, {
          status: editingRecord.status,
          actual_start: editingRecord.actual_start,
          actual_end: editingRecord.actual_end,
          completion_notes: editingRecord.completion_notes,
          actual_cost: editingRecord.actual_cost,
        });
        toast.success('Maintenance record updated successfully');
      } else {
        await advancedRoomService.createMaintenanceRecord(dataToSubmit);
        toast.success('Maintenance record created successfully');
      }
      
      setShowModal(false);
      resetForm();
      fetchRecords();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to save maintenance record');
    }
  };

  const handleEdit = (record: MaintenanceRecord) => {
    setEditingRecord(record);
    // For editing, we can only update status and completion fields
    setFormData({
      room_id: record.room_id,
      maintenance_type: record.maintenance_type,
      title: record.title,
      description: record.description || '',
      scheduled_start: new Date(record.scheduled_start),
      scheduled_end: record.scheduled_end ? new Date(record.scheduled_end) : null,
      assigned_to: record.assigned_to || 0,
      priority: record.priority,
      estimated_cost: record.estimated_cost || 0,
      blocks_room: record.blocks_room,
      block_start: record.block_start ? new Date(record.block_start) : null,
      block_end: record.block_end ? new Date(record.block_end) : null,
      notes: record.notes || '',
    });
    setShowModal(true);
  };

  const handleStatusUpdate = async (recordId: number, newStatus: string) => {
    try {
      await advancedRoomService.updateMaintenanceRecord(recordId, {
        status: newStatus,
      });
      toast.success('Maintenance status updated successfully');
      fetchRecords();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to update status');
    }
  };

  const resetForm = () => {
    setEditingRecord(null);
    setFormData({
      room_id: 0,
      maintenance_type: 'preventive',
      title: '',
      description: '',
      scheduled_start: new Date(),
      scheduled_end: null,
      assigned_to: 0,
      priority: 'medium',
      estimated_cost: 0,
      blocks_room: true,
      block_start: null,
      block_end: null,
      notes: '',
    });
  };

  const getStatusBadge = (status: string) => {
    const statusObj = statuses.find((s) => s.value === status);
    return statusObj || statuses[0];
  };

  const getTypeBadge = (type: string) => {
    const typeObj = maintenanceTypes.find((t) => t.value === type);
    return typeObj || maintenanceTypes[0];
  };

  const getPriorityBadge = (priority: string) => {
    const priorityObj = priorities.find((p) => p.value === priority);
    return priorityObj || priorities[1];
  };

  const getActiveRecords = () => records.filter((r) => ['scheduled', 'in_progress', 'on_hold'].includes(r.status)).length;
  const getCompletedRecords = () => records.filter((r) => r.status === 'completed').length;
  const getEmergencyRecords = () => records.filter((r) => r.maintenance_type === 'emergency' && ['scheduled', 'in_progress'].includes(r.status)).length;

  if (loading && records.length === 0) {
    return <Loading fullScreen text="Loading maintenance records..." />;
  }

  return (
    <div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 animate-fade-in">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="h-1 w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
            <h1 className="text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Maintenance Management
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">Manage room maintenance and repairs</p>
        </div>
        <button
          onClick={() => {
            resetForm();
            setShowModal(true);
          }}
          className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl"
        >
          <Plus className="w-5 h-5" />
          New Maintenance
        </button>
      </div>

      {/* Filters */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in">
        <div className="grid grid-cols-1 md:grid-cols-5 gap-5">
          <div className="relative group">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5 group-focus-within:text-amber-500 transition-colors" />
            <input
              type="text"
              placeholder="Search maintenance..."
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 placeholder-slate-400 font-medium shadow-sm hover:shadow-md"
            />
          </div>
          <select
            value={filters.status}
            onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All Statuses</option>
            {statuses.map((status) => (
              <option key={status.value} value={status.value}>
                {status.label}
              </option>
            ))}
          </select>
          <select
            value={filters.maintenance_type}
            onChange={(e) => setFilters({ ...filters, maintenance_type: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All Types</option>
            {maintenanceTypes.map((type) => (
              <option key={type.value} value={type.value}>
                {type.label}
              </option>
            ))}
          </select>
          <select
            value={filters.room_id}
            onChange={(e) => setFilters({ ...filters, room_id: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All Rooms</option>
            {rooms.map((room) => (
              <option key={room.id} value={room.id}>
                Room {room.room_number}
              </option>
            ))}
          </select>
          <select
            value={filters.priority}
            onChange={(e) => setFilters({ ...filters, priority: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All Priorities</option>
            {priorities.map((priority) => (
              <option key={priority.value} value={priority.value}>
                {priority.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 animate-fade-in">
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Total Records</p>
              <p className="text-3xl font-bold text-slate-900 mt-2">{totalItems}</p>
            </div>
            <Wrench className="w-12 h-12 text-amber-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Active</p>
              <p className="text-3xl font-bold text-blue-600 mt-2">{getActiveRecords()}</p>
            </div>
            <Clock className="w-12 h-12 text-blue-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Completed</p>
              <p className="text-3xl font-bold text-green-600 mt-2">{getCompletedRecords()}</p>
            </div>
            <CheckCircle className="w-12 h-12 text-green-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Emergency</p>
              <p className="text-3xl font-bold text-red-600 mt-2">{getEmergencyRecords()}</p>
            </div>
            <AlertTriangle className="w-12 h-12 text-red-500" />
          </div>
        </div>
      </div>

      {/* Records Table */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 overflow-hidden animate-fade-in">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gradient-to-r from-slate-50 to-gray-50 border-b-2 border-slate-200">
              <tr>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Maintenance
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Room
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Type
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Scheduled
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Priority
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Assigned To
                </th>
                <th className="px-6 py-4 text-right text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-slate-200">
              {records.map((record) => {
                const statusBadge = getStatusBadge(record.status);
                const typeBadge = getTypeBadge(record.maintenance_type);
                const priorityBadge = getPriorityBadge(record.priority);
                return (
                  <tr key={record.id} className="hover:bg-slate-50 transition-colors">
                    <td className="px-6 py-4">
                      <div>
                        <div className="font-semibold text-slate-900">{record.title}</div>
                        {record.description && (
                          <div className="text-sm text-slate-500 mt-1 line-clamp-2">{record.description}</div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="font-semibold text-slate-900">Room {record.room_number || record.room_id}</div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`px-3 py-1 rounded-full text-sm font-medium ${typeBadge.color}`}>
                        {typeBadge.label}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-slate-900 font-medium">
                        {formatDate(record.scheduled_start)}
                      </div>
                      {record.scheduled_end && (
                        <div className="text-xs text-slate-500 mt-1">
                          Until: {formatDate(record.scheduled_end)}
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <span className={`px-3 py-1 rounded-full text-sm font-medium ${statusBadge.color}`}>
                        {statusBadge.label}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`px-3 py-1 rounded-full text-sm font-medium ${priorityBadge.color}`}>
                        {priorityBadge.label}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-slate-600">
                      {record.assigned_staff_name || 'Unassigned'}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handleEdit(record)}
                          className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                          title="Edit"
                        >
                          <Edit className="w-5 h-5" />
                        </button>
                        {record.status !== 'completed' && record.status !== 'cancelled' && (
                          <select
                            value={record.status}
                            onChange={(e) => handleStatusUpdate(record.id, e.target.value)}
                            className="px-3 py-1.5 text-sm border-2 border-slate-200 rounded-lg focus:border-amber-400 cursor-pointer"
                            onClick={(e) => e.stopPropagation()}
                          >
                            {statuses.map((status) => (
                              <option key={status.value} value={status.value}>
                                {status.label}
                              </option>
                            ))}
                          </select>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {records.length === 0 && !loading && (
          <div className="text-center py-12">
            <Wrench className="w-16 h-16 text-slate-400 mx-auto mb-4" />
            <p className="text-slate-600 text-lg">No maintenance records found</p>
          </div>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
        />
      )}

      {/* Create/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
          <div className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
            <div className="sticky top-0 bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between">
              <h2 className="text-2xl font-bold text-slate-900">
                {editingRecord ? 'Edit Maintenance Record' : 'Create Maintenance Record'}
              </h2>
              <button
                onClick={() => {
                  setShowModal(false);
                  resetForm();
                }}
                className="p-2 hover:bg-slate-100 rounded-lg transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>
            <form onSubmit={handleSubmit} className="p-6 space-y-6">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Room *
                  </label>
                  <select
                    value={formData.room_id}
                    onChange={(e) => setFormData({ ...formData, room_id: parseInt(e.target.value) || 0 })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    required
                    disabled={!!editingRecord}
                  >
                    <option value={0}>Select Room</option>
                    {rooms.map((room) => (
                      <option key={room.id} value={room.id}>
                        Room {room.room_number} ({room.room_type?.name || 'Unknown'})
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Maintenance Type *
                  </label>
                  <select
                    value={formData.maintenance_type}
                    onChange={(e) => setFormData({ ...formData, maintenance_type: e.target.value })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    required
                  >
                    {maintenanceTypes.map((type) => (
                      <option key={type.value} value={type.value}>
                        {type.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Title *
                </label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                  className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Description
                </label>
                <textarea
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  rows={3}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Scheduled Start *
                  </label>
                  <DatePicker
                    selected={formData.scheduled_start}
                    onChange={(date: Date) => setFormData({ ...formData, scheduled_start: date })}
                    showTimeSelect
                    dateFormat="MMMM d, yyyy h:mm aa"
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Scheduled End
                  </label>
                  <DatePicker
                    selected={formData.scheduled_end}
                    onChange={(date: Date | null) => setFormData({ ...formData, scheduled_end: date })}
                    showTimeSelect
                    dateFormat="MMMM d, yyyy h:mm aa"
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Assigned To
                  </label>
                  <select
                    value={formData.assigned_to}
                    onChange={(e) => setFormData({ ...formData, assigned_to: parseInt(e.target.value) || 0 })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  >
                    <option value={0}>Unassigned</option>
                    {staffMembers.map((staff) => (
                      <option key={staff.id} value={staff.id}>
                        {staff.full_name}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Priority *
                  </label>
                  <select
                    value={formData.priority}
                    onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    required
                  >
                    {priorities.map((priority) => (
                      <option key={priority.value} value={priority.value}>
                        {priority.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Estimated Cost
                  </label>
                  <input
                    type="number"
                    value={formData.estimated_cost}
                    onChange={(e) => setFormData({ ...formData, estimated_cost: parseFloat(e.target.value) || 0 })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    min="0"
                    step="0.01"
                  />
                </div>
                <div className="flex items-center pt-8">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={formData.blocks_room}
                      onChange={(e) => setFormData({ ...formData, blocks_room: e.target.checked })}
                      className="w-5 h-5 text-amber-600 rounded"
                    />
                    <span className="text-slate-700 font-medium">Blocks Room</span>
                  </label>
                </div>
              </div>

              {formData.blocks_room && (
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      Block Start
                    </label>
                    <DatePicker
                      selected={formData.block_start}
                      onChange={(date: Date | null) => setFormData({ ...formData, block_start: date })}
                      showTimeSelect
                      dateFormat="MMMM d, yyyy h:mm aa"
                      className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">
                      Block End
                    </label>
                    <DatePicker
                      selected={formData.block_end}
                      onChange={(date: Date | null) => setFormData({ ...formData, block_end: date })}
                      showTimeSelect
                      dateFormat="MMMM d, yyyy h:mm aa"
                      className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    />
                  </div>
                </div>
              )}

              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Notes
                </label>
                <textarea
                  value={formData.notes}
                  onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                  className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  rows={3}
                />
              </div>

              <div className="flex gap-4 pt-4 border-t border-slate-200">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="flex-1 px-6 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all"
                >
                  {editingRecord ? 'Update Record' : 'Create Record'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default MaintenanceManagementPage;

