import React, { useState, useEffect } from 'react';
import {
  Plus,
  Edit,
  Eye,
  Search,
  X,
  CheckCircle,
  Clock,
  RefreshCw,
  Play,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../../shared/components/Loading';
import Pagination from '../../../shared/components/Pagination';
import advancedRoomService, { HousekeepingTask, ChecklistItem } from '../../rooms/services/advancedRoomService';
import roomService, { Room } from '../../rooms/services/roomService';
import userService, { User as UserType } from '../../auth/services/userService';
import useAuthStore from '../../../store/useAuthStore';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

const HousekeepingManagement: React.FC = () => {
  const { userInfo } = useAuthStore();
  const isAdmin = userInfo?.role === 'admin';
  const isHousekeeping = userInfo?.role === 'housekeeping';
  const [loading, setLoading] = useState(true);
  const [tasks, setTasks] = useState<HousekeepingTask[]>([]);
  const [rooms, setRooms] = useState<Room[]>([]);
  const [staff, setStaff] = useState<UserType[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [editingTask, setEditingTask] = useState<HousekeepingTask | null>(null);
  const [viewingTask, setViewingTask] = useState<HousekeepingTask | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [filters, setFilters] = useState({
    room_id: '',
    status: '',
    task_type: '',
    date: '',
  });

  const [formData, setFormData] = useState({
    room_id: '',
    booking_id: '',
    task_type: 'vacant' as 'checkout' | 'stayover' | 'vacant' | 'inspection' | 'turndown',
    scheduled_time: new Date(),
    assigned_to: '',
    checklist_items: [] as ChecklistItem[],
    notes: '',
    estimated_duration_minutes: '',
  });

  const defaultChecklistItems: Record<string, string[]> = {
    checkout: ['Bathroom cleaned', 'Beds made', 'Trash emptied', 'Towels replaced', 'Amenities restocked', 'Floor vacuumed'],
    stayover: ['Beds made', 'Trash emptied', 'Towels replaced', 'Bathroom cleaned'],
    vacant: ['Deep clean bathroom', 'Change linens', 'Vacuum and mop', 'Dust surfaces', 'Check amenities'],
    inspection: ['Check all amenities', 'Test electronics', 'Check for damages', 'Verify cleanliness'],
    turndown: ['Prepare bed', 'Close curtains', 'Place amenities', 'Adjust lighting'],
  };

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

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

  // Auto-refresh every 30 seconds for real-time updates
  useEffect(() => {
    const interval = setInterval(() => {
      fetchTasks();
    }, 30000); // Refresh every 30 seconds

    return () => clearInterval(interval);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, filters]);

  const fetchTasks = async () => {
    try {
      setLoading(true);
      const params: { page: number; limit: number; room_id?: number; status?: string } = { 
        page: currentPage, 
        limit: 10,
        include_cleaning_rooms: true  // Include rooms in cleaning status
      };
      if (filters.room_id) params.room_id = parseInt(filters.room_id);
      if (filters.status) params.status = filters.status;
      if (filters.task_type) params.task_type = filters.task_type;
      if (filters.date) params.date = filters.date;

      const response = await advancedRoomService.getHousekeepingTasks(params);
      if (response.status === 'success') {
        setTasks(response.data.tasks);
        setTotalPages(response.data.pagination?.total_pages || 1);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to fetch housekeeping tasks');
    } finally {
      setLoading(false);
    }
  };

  const fetchRooms = async () => {
    try {
      const allRooms: Room[] = [];
      let page = 1;
      let hasMorePages = true;

      while (hasMorePages) {
        const response = await roomService.getRooms({ limit: 100, page });
        if (response.success || response.status === 'success') {
          if (response.data?.rooms) {
            allRooms.push(...response.data.rooms);
            
            // Check if there are more pages
            if (response.data.pagination) {
              hasMorePages = page < response.data.pagination.totalPages;
              page++;
            } else {
              hasMorePages = false;
            }
          } else {
            hasMorePages = false;
          }
        } else {
          console.error('Failed to fetch rooms: Invalid response structure', response);
          hasMorePages = false;
        }
      }

      setRooms(allRooms);
    } catch (error) {
      console.error('Failed to fetch rooms:', error);
      toast.error('Failed to load rooms. Please try again.');
    }
  };

  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 = () => {
    setEditingTask(null);
    setFormData({
      room_id: '',
      booking_id: '',
      task_type: 'vacant',
      scheduled_time: new Date(),
      assigned_to: '',
      checklist_items: [],
      notes: '',
      estimated_duration_minutes: '',
    });
    // Ensure rooms are loaded when opening the modal
    if (rooms.length === 0) {
      fetchRooms();
    }
    setShowModal(true);
  };

  const handleTaskTypeChange = (type: string) => {
    const items = defaultChecklistItems[type] || [];
    setFormData({
      ...formData,
      task_type: type as 'cleaning' | 'inspection' | 'maintenance',
      checklist_items: items.map(item => ({ item, completed: false, notes: '' })),
    });
  };

  const handleEdit = (task: HousekeepingTask) => {
    setEditingTask(task);
    setFormData({
      room_id: task.room_id.toString(),
      booking_id: task.booking_id?.toString() || '',
      task_type: task.task_type,
      scheduled_time: new Date(task.scheduled_time),
      assigned_to: task.assigned_to?.toString() || '',
      checklist_items: task.checklist_items || [],
      notes: task.notes || '',
      estimated_duration_minutes: task.estimated_duration_minutes?.toString() || '',
    });
    setShowModal(true);
  };

  const handleStartTask = async (task: HousekeepingTask) => {
    if (!task.id) {
      toast.error('Cannot start task: Invalid task ID');
      return;
    }

    try {
      await advancedRoomService.updateHousekeepingTask(task.id, {
        status: 'in_progress',
        assigned_to: userInfo?.id,  // Assign to current user when starting
      });
      toast.success('Task started successfully');
      fetchTasks();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to start task');
    }
  };

  const handleMarkAsDone = async (task: HousekeepingTask) => {
    if (!task.id) {
      toast.error('Cannot complete task: Invalid task ID');
      return;
    }

    // Double check that the task is assigned to the current user
    if (!task.assigned_to) {
      toast.error('Task must be assigned before it can be marked as done');
      return;
    }
    if (task.assigned_to !== userInfo?.id) {
      toast.error('Only the assigned staff member can mark this task as done');
      return;
    }

    try {
      await advancedRoomService.updateHousekeepingTask(task.id, {
        status: 'completed',
        checklist_items: task.checklist_items?.map(item => ({ ...item, completed: true })) || [],
      });
      toast.success('Task marked as completed successfully. Room is now ready for check-in.');
      fetchTasks();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to mark task as done');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingTask && editingTask.id) {
        // For staff, only allow updating status and checklist items
        if (!isAdmin) {
          const data = {
            status: editingTask.status,
            checklist_items: formData.checklist_items,
            notes: formData.notes, // Allow staff to add notes
          };
          await advancedRoomService.updateHousekeepingTask(editingTask.id, data);
        } else {
          // Admin can update all fields
          const data = {
            room_id: parseInt(formData.room_id),
            booking_id: formData.booking_id ? parseInt(formData.booking_id) : undefined,
            task_type: formData.task_type,
            scheduled_time: formData.scheduled_time.toISOString(),
            assigned_to: formData.assigned_to ? parseInt(formData.assigned_to) : undefined,
            checklist_items: formData.checklist_items,
            notes: formData.notes,
            estimated_duration_minutes: formData.estimated_duration_minutes ? parseInt(formData.estimated_duration_minutes) : undefined,
            status: editingTask.status,
          };
          await advancedRoomService.updateHousekeepingTask(editingTask.id, data);
        }
        toast.success('Housekeeping task updated successfully');
      } else {
        // Only admin and staff can create tasks
        if (!isAdmin && userInfo?.role !== 'staff') {
          toast.error('You do not have permission to create tasks');
          return;
        }
        const data = {
          room_id: parseInt(formData.room_id),
          booking_id: formData.booking_id ? parseInt(formData.booking_id) : undefined,
          task_type: formData.task_type,
          scheduled_time: formData.scheduled_time.toISOString(),
          assigned_to: formData.assigned_to ? parseInt(formData.assigned_to) : undefined,
          checklist_items: formData.checklist_items,
          notes: formData.notes,
          estimated_duration_minutes: formData.estimated_duration_minutes ? parseInt(formData.estimated_duration_minutes) : undefined,
        };
        await advancedRoomService.createHousekeepingTask(data);
        toast.success('Housekeeping task created successfully');
      }

      setShowModal(false);
      fetchTasks();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to save housekeeping task');
    }
  };

  const updateChecklistItem = (index: number, field: 'completed' | 'notes', value: boolean | string) => {
    const updated = [...formData.checklist_items];
    updated[index] = { ...updated[index], [field]: value };
    setFormData({ ...formData, checklist_items: updated });
  };

  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 'pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'skipped':
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  if (loading && tasks.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="pending">Pending</option>
            <option value="in_progress">In Progress</option>
            <option value="completed">Completed</option>
            <option value="skipped">Skipped</option>
          </select>
          <select
            value={filters.task_type}
            onChange={(e) => setFilters({ ...filters, task_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="checkout">Checkout</option>
            <option value="stayover">Stayover</option>
            <option value="vacant">Vacant</option>
            <option value="inspection">Inspection</option>
            <option value="turndown">Turndown</option>
          </select>
          <input
            type="date"
            value={filters.date}
            onChange={(e) => setFilters({ ...filters, date: 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"
          />
        </div>
        <div className="flex items-center space-x-2">
          <button
            onClick={fetchTasks}
            disabled={loading}
            className="flex items-center space-x-2 px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors disabled:opacity-50"
            title="Refresh tasks"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            <span>Refresh</span>
          </button>
          {(isAdmin || userInfo?.role === 'staff') && (
            <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 Task</span>
            </button>
          )}
        </div>
      </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">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">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">Progress</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">
            {tasks.map((task, index) => {
              const completedItems = task.checklist_items?.filter(item => item.completed).length || 0;
              const totalItems = task.checklist_items?.length || 0;
              const progress = totalItems > 0 ? Math.round((completedItems / totalItems) * 100) : 0;
              const isRoomStatusOnly = task.is_room_status_only || task.id === null;
              const isCleaningRoom = task.room_status === 'cleaning' || isRoomStatusOnly;

              return (
                <tr 
                  key={task.id || `room-${task.room_id}-${index}`} 
                  className={`hover:bg-gray-50 ${isCleaningRoom ? 'bg-amber-50/50' : ''}`}
                >
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center space-x-2">
                      <div className="text-sm font-medium text-gray-900">
                        {task.room_number || `Room ${task.room_id}`}
                      </div>
                      {isCleaningRoom && (
                        <span className="px-2 py-0.5 text-xs font-semibold rounded-full bg-amber-100 text-amber-800 border border-amber-200">
                          Cleaning
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-500 capitalize">
                      {isRoomStatusOnly ? 'Room Status' : task.task_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(task.status)}`}>
                      {task.status.replace('_', ' ')}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {task.scheduled_time ? new Date(task.scheduled_time).toLocaleString() : 'N/A'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {task.assigned_staff_name || (isRoomStatusOnly ? 'Not Assigned' : 'Unassigned')}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {totalItems > 0 ? (
                      <div className="flex items-center">
                        <div className="w-16 bg-gray-200 rounded-full h-2 mr-2">
                          <div
                            className="bg-blue-600 h-2 rounded-full"
                            style={{ width: `${progress}%` }}
                          />
                        </div>
                        <span className="text-xs text-gray-600">{progress}%</span>
                      </div>
                    ) : (
                      <span className="text-xs text-gray-400">No checklist</span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex items-center space-x-2">
                      {task.id && (
                        <button
                          onClick={() => setViewingTask(task)}
                          className="text-blue-600 hover:text-blue-900"
                          title="View task"
                        >
                          <Eye className="w-4 h-4" />
                        </button>
                      )}
                      {isRoomStatusOnly ? (
                        // For room status entries, allow creating a task
                        (isAdmin || userInfo?.role === 'staff') && (
                          <button
                            onClick={() => {
                              setFormData({
                                room_id: task.room_id.toString(),
                                booking_id: '',
                                task_type: 'vacant',
                                scheduled_time: new Date(),
                                assigned_to: '',
                                checklist_items: [],
                                notes: '',
                                estimated_duration_minutes: '',
                              });
                              setEditingTask(null);
                              setShowModal(true);
                            }}
                            className="text-indigo-600 hover:text-indigo-900"
                            title="Create task for this room"
                          >
                            <Plus className="w-4 h-4" />
                          </button>
                        )
                      ) : (
                        // For actual tasks
                        isAdmin ? (
                          <button
                            onClick={() => handleEdit(task)}
                            className="text-indigo-600 hover:text-indigo-900"
                            title="Edit task"
                          >
                            <Edit className="w-4 h-4" />
                          </button>
                        ) : (
                          // Housekeeping and staff actions
                          (isHousekeeping || userInfo?.role === 'staff') && (
                            <>
                              {task.status === 'pending' && !task.assigned_to && (
                                // Show Start button for unassigned pending tasks
                                <button
                                  onClick={() => handleStartTask(task)}
                                  className="text-blue-600 hover:text-blue-900"
                                  title="Start cleaning this room"
                                >
                                  <Play className="w-4 h-4" />
                                </button>
                              )}
                              {task.assigned_to === userInfo?.id && task.status !== 'completed' && (
                                <>
                                  <button
                                    onClick={() => handleEdit(task)}
                                    className="text-indigo-600 hover:text-indigo-900"
                                    title="Update task"
                                  >
                                    <Edit className="w-4 h-4" />
                                  </button>
                                  {task.status === 'in_progress' && (
                                    <button
                                      onClick={() => handleMarkAsDone(task)}
                                      className="text-green-600 hover:text-green-900"
                                      title="Mark as done - Room ready for check-in"
                                    >
                                      <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-3xl 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">
                  {editingTask 
                    ? (isAdmin ? 'Edit Housekeeping Task' : 'Update Task Status')
                    : 'New Housekeeping Task'}
                </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
                    disabled={!isAdmin && editingTask !== null}
                    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 ${!isAdmin && editingTask !== null ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                  >
                    <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">Task Type *</label>
                  <select
                    required
                    disabled={!isAdmin && editingTask !== null}
                    value={formData.task_type}
                    onChange={(e) => handleTaskTypeChange(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 ${!isAdmin && editingTask !== null ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                  >
                    <option value="checkout">Checkout</option>
                    <option value="stayover">Stayover</option>
                    <option value="vacant">Vacant</option>
                    <option value="inspection">Inspection</option>
                    <option value="turndown">Turndown</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">Scheduled Time *</label>
                  <DatePicker
                    selected={formData.scheduled_time}
                    onChange={(date: Date | null) => date && setFormData({ ...formData, scheduled_time: date })}
                    showTimeSelect
                    dateFormat="yyyy-MM-dd HH:mm"
                    disabled={!isAdmin && editingTask !== null}
                    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 ${!isAdmin && editingTask !== null ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Assigned To</label>
                  <select
                    disabled={!isAdmin}
                    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 ${!isAdmin ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                  >
                    <option value="">Unassigned</option>
                    {staff.map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.full_name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Status field - staff can update this */}
              {editingTask && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Status *</label>
                  <select
                    required
                    value={editingTask.status}
                    onChange={(e) => {
                      if (editingTask) {
                        setEditingTask({ ...editingTask, status: e.target.value as 'pending' | 'in_progress' | 'completed' | 'cancelled' });
                      }
                    }}
                    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="pending">Pending</option>
                    <option value="in_progress">In Progress</option>
                    <option value="completed">Completed</option>
                    <option value="skipped">Skipped</option>
                  </select>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Checklist Items</label>
                <div className="space-y-2 border border-gray-200 rounded-md p-4 max-h-64 overflow-y-auto">
                  {formData.checklist_items.map((item, index) => (
                    <div key={index} className="flex items-start space-x-3">
                      <input
                        type="checkbox"
                        checked={item.completed}
                        onChange={(e) => updateChecklistItem(index, 'completed', e.target.checked)}
                        className="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                      />
                      <div className="flex-1">
                        <label className="text-sm text-gray-700">{item.item}</label>
                        <input
                          type="text"
                          placeholder="Notes (optional)"
                          value={item.notes || ''}
                          onChange={(e) => updateChecklistItem(index, 'notes', e.target.value)}
                          className="mt-1 w-full border border-gray-300 rounded-md px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-blue-500"
                        />
                      </div>
                    </div>
                  ))}
                  {formData.checklist_items.length === 0 && (
                    <p className="text-sm text-gray-500">Select a task type to load checklist items</p>
                  )}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Estimated Duration (minutes)</label>
                <input
                  type="number"
                  disabled={!isAdmin && editingTask !== null}
                  value={formData.estimated_duration_minutes}
                  onChange={(e) => setFormData({ ...formData, estimated_duration_minutes: 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 ${!isAdmin && editingTask !== null ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                />
              </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={3}
                  placeholder={!isAdmin && editingTask ? "Add notes about the task..." : ""}
                  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"
                >
                  {editingTask ? 'Update' : 'Create'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* View Modal */}
      {viewingTask && (
        <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">Task Details</h2>
                <button
                  onClick={() => setViewingTask(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">{viewingTask.room_number || `Room ${viewingTask.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(viewingTask.status)}`}>
                      {viewingTask.status.replace('_', ' ')}
                    </span>
                  </p>
                </div>
              </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">{viewingTask.task_type}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-500">Scheduled Time</label>
                  <p className="mt-1 text-sm text-gray-900">{new Date(viewingTask.scheduled_time).toLocaleString()}</p>
                </div>
              </div>

              {viewingTask.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">{viewingTask.assigned_staff_name}</p>
                </div>
              )}

              {viewingTask.checklist_items && viewingTask.checklist_items.length > 0 && (
                <div>
                  <label className="block text-sm font-medium text-gray-500 mb-2">Checklist</label>
                  <div className="space-y-2">
                    {viewingTask.checklist_items.map((item, index) => (
                      <div key={index} className="flex items-start space-x-2">
                        {item.completed ? (
                          <CheckCircle className="w-5 h-5 text-green-500 mt-0.5" />
                        ) : (
                          <Clock className="w-5 h-5 text-gray-400 mt-0.5" />
                        )}
                        <div className="flex-1">
                          <p className={`text-sm ${item.completed ? 'text-gray-500 line-through' : 'text-gray-900'}`}>
                            {item.item}
                          </p>
                          {item.notes && (
                            <p className="text-xs text-gray-500 mt-1">{item.notes}</p>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

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

              <div className="flex justify-end pt-4 border-t border-gray-200">
                <button
                  onClick={() => {
                    setViewingTask(null);
                    handleEdit(viewingTask);
                  }}
                  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 HousekeepingManagement;

