import React, { useState, useEffect } from 'react';
import {
  Plus,
  Edit,
  Eye,
  Search,
  X,
  CheckCircle,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../common/Loading';
import Pagination from '../common/Pagination';
import advancedRoomService, { MaintenanceRecord } from '../../services/api/advancedRoomService';
import { roomService, Room } from '../../services/api';
import { userService, User as UserType } from '../../services/api';
import useAuthStore from '../../store/useAuthStore';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

const MaintenanceManagement: React.FC = () => {
  const { userInfo } = useAuthStore();
  const isAdmin = userInfo?.role === 'admin';
  const [loading, setLoading] = useState(true);
  const [maintenanceRecords, setMaintenanceRecords] = useState<MaintenanceRecord[]>([]);
  const [rooms, setRooms] = useState<Room[]>([]);
  const [staff, setStaff] = useState<UserType[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [editingRecord, setEditingRecord] = useState<MaintenanceRecord | null>(null);
  const [viewingRecord, setViewingRecord] = useState<MaintenanceRecord | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [filters, setFilters] = useState({
    room_id: '',
    status: '',
    maintenance_type: '',
  });

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

  useEffect(() => {
    fetchMaintenanceRecords();
    fetchRooms();
    fetchStaff();
  }, [currentPage, filters]);

  const fetchMaintenanceRecords = async () => {
    try {
      setLoading(true);
      const params: any = { page: currentPage, limit: 10 };
      if (filters.room_id) params.room_id = parseInt(filters.room_id);
      if (filters.status) params.status = filters.status;
      if (filters.maintenance_type) params.maintenance_type = filters.maintenance_type;

      const response = await advancedRoomService.getMaintenanceRecords(params);
      if (response.status === 'success') {
        setMaintenanceRecords(response.data.maintenance_records);
        setTotalPages(response.data.pagination?.total_pages || 1);
      }
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Failed to fetch maintenance records');
    } finally {
      setLoading(false);
    }
  };

  const fetchRooms = async () => {
    try {
      const response = await roomService.getRooms({ limit: 1000, page: 1 });
      if (response.data?.rooms) {
        setRooms(response.data.rooms);
      }
    } catch (error) {
      console.error('Failed to fetch rooms:', error);
    }
  };

  const fetchStaff = async () => {
    try {
      const response = await userService.getUsers({ role: 'staff', limit: 100 });
      if (response.data?.users) {
        setStaff(response.data.users);
      }
    } catch (error) {
      console.error('Failed to fetch staff:', error);
    }
  };

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

  const handleMarkAsDone = async (record: MaintenanceRecord) => {
    // Double check that the maintenance is assigned to the current user
    if (!record.assigned_to) {
      toast.error('Maintenance must be assigned before it can be marked as done');
      return;
    }
    if (record.assigned_to !== userInfo?.id) {
      toast.error('Only the assigned staff member can mark this maintenance as done');
      return;
    }

    try {
      await advancedRoomService.updateMaintenanceRecord(record.id, {
        status: 'completed',
        actual_end: new Date().toISOString(),
      });
      toast.success('Maintenance marked as completed successfully');
      fetchMaintenanceRecords();
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Failed to mark maintenance as done');
    }
  };

  const handleEdit = (record: MaintenanceRecord) => {
    setEditingRecord(record);
    setFormData({
      room_id: record.room_id.toString(),
      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?.toString() || '',
      estimated_cost: record.estimated_cost?.toString() || '',
      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,
      priority: record.priority as any,
      notes: record.notes || '',
    });
    setShowModal(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const data = {
        room_id: parseInt(formData.room_id),
        maintenance_type: formData.maintenance_type,
        title: formData.title,
        description: formData.description,
        scheduled_start: formData.scheduled_start.toISOString(),
        scheduled_end: formData.scheduled_end?.toISOString(),
        assigned_to: formData.assigned_to ? parseInt(formData.assigned_to) : undefined,
        estimated_cost: formData.estimated_cost ? parseFloat(formData.estimated_cost) : undefined,
        blocks_room: formData.blocks_room,
        block_start: formData.block_start?.toISOString(),
        block_end: formData.block_end?.toISOString(),
        priority: formData.priority,
        notes: formData.notes,
      };

      if (editingRecord) {
        await advancedRoomService.updateMaintenanceRecord(editingRecord.id, {
          status: editingRecord.status,
          ...data,
        });
        toast.success('Maintenance record updated successfully');
      } else {
        await advancedRoomService.createMaintenanceRecord(data);
        toast.success('Maintenance record created successfully');
      }

      setShowModal(false);
      fetchMaintenanceRecords();
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Failed to save maintenance record');
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'bg-green-100 text-green-800';
      case 'in_progress':
        return 'bg-blue-100 text-blue-800';
      case 'scheduled':
        return 'bg-yellow-100 text-yellow-800';
      case 'cancelled':
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'urgent':
        return 'bg-red-100 text-red-800';
      case 'high':
        return 'bg-orange-100 text-orange-800';
      case 'medium':
        return 'bg-yellow-100 text-yellow-800';
      case 'low':
        return 'bg-green-100 text-green-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  if (loading && maintenanceRecords.length === 0) {
    return <Loading />;
  }

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <div className="flex items-center space-x-2">
            <Search className="w-5 h-5 text-gray-500" />
            <input
              type="text"
              placeholder="Search by room..."
              className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              onChange={(e) => setFilters({ ...filters, room_id: e.target.value })}
            />
          </div>
          <select
            value={filters.status}
            onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">All Statuses</option>
            <option value="scheduled">Scheduled</option>
            <option value="in_progress">In Progress</option>
            <option value="completed">Completed</option>
            <option value="cancelled">Cancelled</option>
          </select>
          <select
            value={filters.maintenance_type}
            onChange={(e) => setFilters({ ...filters, maintenance_type: e.target.value })}
            className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">All Types</option>
            <option value="preventive">Preventive</option>
            <option value="corrective">Corrective</option>
            <option value="emergency">Emergency</option>
            <option value="upgrade">Upgrade</option>
            <option value="inspection">Inspection</option>
          </select>
        </div>
        {isAdmin && (
          <button
            onClick={handleCreate}
            className="flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            <Plus className="w-4 h-4" />
            <span>New Maintenance</span>
          </button>
        )}
      </div>

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Room</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Title</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Priority</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Scheduled</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Assigned</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {maintenanceRecords.map((record) => (
              <tr key={record.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm font-medium text-gray-900">{record.room_number || `Room ${record.room_id}`}</div>
                </td>
                <td className="px-6 py-4">
                  <div className="text-sm text-gray-900">{record.title}</div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm text-gray-500 capitalize">{record.maintenance_type}</div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(record.status)}`}>
                    {record.status.replace('_', ' ')}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getPriorityColor(record.priority)}`}>
                    {record.priority}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {new Date(record.scheduled_start).toLocaleDateString()}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {record.assigned_staff_name || 'Unassigned'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <div className="flex items-center space-x-2">
                    <button
                      onClick={() => setViewingRecord(record)}
                      className="text-blue-600 hover:text-blue-900"
                      title="View maintenance"
                    >
                      <Eye className="w-4 h-4" />
                    </button>
                    {isAdmin ? (
                      <button
                        onClick={() => handleEdit(record)}
                        className="text-indigo-600 hover:text-indigo-900"
                        title="Edit maintenance"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                    ) : (
                      // Staff can mark their own assigned maintenance as done
                      record.assigned_to === userInfo?.id && record.status !== 'completed' && (
                        <button
                          onClick={() => handleMarkAsDone(record)}
                          className="text-green-600 hover:text-green-900"
                          title="Mark as done"
                        >
                          <CheckCircle className="w-4 h-4" />
                        </button>
                      )
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className="mt-4">
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={setCurrentPage}
          />
        </div>
      )}

      {/* Create/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-gray-200">
              <div className="flex items-center justify-between">
                <h2 className="text-2xl font-bold text-gray-900">
                  {editingRecord ? 'Edit Maintenance' : 'New Maintenance'}
                </h2>
                <button
                  onClick={() => setShowModal(false)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>
            </div>

            <form onSubmit={handleSubmit} className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Room *</label>
                  <select
                    required
                    value={formData.room_id}
                    onChange={(e) => setFormData({ ...formData, room_id: e.target.value })}
                    className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">Select Room</option>
                    {rooms.map((room) => (
                      <option key={room.id} value={room.id}>
                        {room.room_number} - Floor {room.floor}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Type *</label>
                  <select
                    required
                    value={formData.maintenance_type}
                    onChange={(e) => setFormData({ ...formData, maintenance_type: e.target.value as any })}
                    className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="preventive">Preventive</option>
                    <option value="corrective">Corrective</option>
                    <option value="emergency">Emergency</option>
                    <option value="upgrade">Upgrade</option>
                    <option value="inspection">Inspection</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Title *</label>
                <input
                  type="text"
                  required
                  value={formData.title}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
                <textarea
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  rows={3}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Scheduled Start *</label>
                  <DatePicker
                    selected={formData.scheduled_start}
                    onChange={(date: Date | null) => date && setFormData({ ...formData, scheduled_start: date })}
                    showTimeSelect
                    dateFormat="yyyy-MM-dd HH:mm"
                    className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Scheduled End</label>
                  <DatePicker
                    selected={formData.scheduled_end}
                    onChange={(date: Date | null) => setFormData({ ...formData, scheduled_end: date })}
                    showTimeSelect
                    dateFormat="yyyy-MM-dd HH:mm"
                    className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Priority</label>
                  <select
                    value={formData.priority}
                    onChange={(e) => setFormData({ ...formData, priority: e.target.value as any })}
                    className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="low">Low</option>
                    <option value="medium">Medium</option>
                    <option value="high">High</option>
                    <option value="urgent">Urgent</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Assigned To</label>
                  <select
                    value={formData.assigned_to}
                    onChange={(e) => setFormData({ ...formData, assigned_to: e.target.value })}
                    className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">Unassigned</option>
                    {staff.map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.full_name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Estimated Cost</label>
                  <input
                    type="number"
                    step="0.01"
                    value={formData.estimated_cost}
                    onChange={(e) => setFormData({ ...formData, estimated_cost: e.target.value })}
                    className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>

                <div className="flex items-center pt-6">
                  <input
                    type="checkbox"
                    id="blocks_room"
                    checked={formData.blocks_room}
                    onChange={(e) => setFormData({ ...formData, blocks_room: e.target.checked })}
                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <label htmlFor="blocks_room" className="ml-2 block text-sm text-gray-700">
                    Block room during maintenance
                  </label>
                </div>
              </div>

              {formData.blocks_room && (
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Block Start</label>
                    <DatePicker
                      selected={formData.block_start}
                      onChange={(date: Date | null) => setFormData({ ...formData, block_start: date })}
                      showTimeSelect
                      dateFormat="yyyy-MM-dd HH:mm"
                      className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Block End</label>
                    <DatePicker
                      selected={formData.block_end}
                      onChange={(date: Date | null) => setFormData({ ...formData, block_end: date })}
                      showTimeSelect
                      dateFormat="yyyy-MM-dd HH:mm"
                      className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Notes</label>
                <textarea
                  value={formData.notes}
                  onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                  rows={2}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700"
                >
                  {editingRecord ? 'Update' : 'Create'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* View Modal */}
      {viewingRecord && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-gray-200">
              <div className="flex items-center justify-between">
                <h2 className="text-2xl font-bold text-gray-900">Maintenance Details</h2>
                <button
                  onClick={() => setViewingRecord(null)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>
            </div>

            <div className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-500">Room</label>
                  <p className="mt-1 text-sm text-gray-900">{viewingRecord.room_number || `Room ${viewingRecord.room_id}`}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-500">Status</label>
                  <p className="mt-1">
                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(viewingRecord.status)}`}>
                      {viewingRecord.status.replace('_', ' ')}
                    </span>
                  </p>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-500">Title</label>
                <p className="mt-1 text-sm text-gray-900">{viewingRecord.title}</p>
              </div>

              {viewingRecord.description && (
                <div>
                  <label className="block text-sm font-medium text-gray-500">Description</label>
                  <p className="mt-1 text-sm text-gray-900">{viewingRecord.description}</p>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-500">Type</label>
                  <p className="mt-1 text-sm text-gray-900 capitalize">{viewingRecord.maintenance_type}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-500">Priority</label>
                  <p className="mt-1">
                    <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getPriorityColor(viewingRecord.priority)}`}>
                      {viewingRecord.priority}
                    </span>
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-500">Scheduled Start</label>
                  <p className="mt-1 text-sm text-gray-900">{new Date(viewingRecord.scheduled_start).toLocaleString()}</p>
                </div>
                {viewingRecord.scheduled_end && (
                  <div>
                    <label className="block text-sm font-medium text-gray-500">Scheduled End</label>
                    <p className="mt-1 text-sm text-gray-900">{new Date(viewingRecord.scheduled_end).toLocaleString()}</p>
                  </div>
                )}
              </div>

              {viewingRecord.assigned_staff_name && (
                <div>
                  <label className="block text-sm font-medium text-gray-500">Assigned To</label>
                  <p className="mt-1 text-sm text-gray-900">{viewingRecord.assigned_staff_name}</p>
                </div>
              )}

              {(viewingRecord.estimated_cost || viewingRecord.actual_cost) && (
                <div className="grid grid-cols-2 gap-4">
                  {viewingRecord.estimated_cost && (
                    <div>
                      <label className="block text-sm font-medium text-gray-500">Estimated Cost</label>
                      <p className="mt-1 text-sm text-gray-900">${viewingRecord.estimated_cost.toFixed(2)}</p>
                    </div>
                  )}
                  {viewingRecord.actual_cost && (
                    <div>
                      <label className="block text-sm font-medium text-gray-500">Actual Cost</label>
                      <p className="mt-1 text-sm text-gray-900">${viewingRecord.actual_cost.toFixed(2)}</p>
                    </div>
                  )}
                </div>
              )}

              {isAdmin && (
                <div className="flex justify-end pt-4 border-t border-gray-200">
                  <button
                    onClick={() => {
                      setViewingRecord(null);
                      handleEdit(viewingRecord);
                    }}
                    className="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700"
                  >
                    Edit
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MaintenanceManagement;

