import React, { useState, useEffect } from 'react';
import {
  Clock,
  CheckCircle,
  AlertCircle,
  Bell,
  MessageSquare,
  Package,
  Wrench,
  Sparkles,
  RefreshCw,
  Filter,
  MapPin,
  Eye,
  UserCheck,
  X,
  Search,
  ChevronDown,
  ChevronUp,
} from 'lucide-react';
import { toast } from 'react-toastify';
import guestRequestService, { GuestRequest } from '../../features/guestRequests/services/guestRequestService';
import userService, { User as StaffUser } from '../../features/auth/services/userService';
import { formatDate, formatRelativeTime } from '../../shared/utils/format';
import { logger } from '../../shared/utils/logger';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import useAuthStore from '../../store/useAuthStore';
import Pagination from '../../shared/components/Pagination';

const GuestRequestManagementPage: React.FC = () => {
  const { userInfo } = useAuthStore();
  const [loading, setLoading] = useState(true);
  const [requests, setRequests] = useState<GuestRequest[]>([]);
  const [staffMembers, setStaffMembers] = useState<StaffUser[]>([]);
  const [selectedRequest, setSelectedRequest] = useState<GuestRequest | null>(null);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const [filters, setFilters] = useState({
    status: '',
    request_type: '',
    priority: '',
    assigned_to: '',
    room_id: '',
    search: '',
  });
  const [expandedFilters, setExpandedFilters] = useState(false);
  const [updatingRequestId, setUpdatingRequestId] = useState<number | null>(null);
  const [staffNotes, setStaffNotes] = useState('');

  const requestTypes = [
    { value: 'extra_towels', label: 'Extra Towels', icon: Package, color: 'bg-blue-100 text-blue-800' },
    { value: 'extra_pillows', label: 'Extra Pillows', icon: Package, color: 'bg-purple-100 text-purple-800' },
    { value: 'room_cleaning', label: 'Room Cleaning', icon: Sparkles, color: 'bg-green-100 text-green-800' },
    { value: 'turndown_service', label: 'Turndown Service', icon: Sparkles, color: 'bg-indigo-100 text-indigo-800' },
    { value: 'amenities', label: 'Amenities', icon: Package, color: 'bg-pink-100 text-pink-800' },
    { value: 'maintenance', label: 'Maintenance', icon: Wrench, color: 'bg-orange-100 text-orange-800' },
    { value: 'room_service', label: 'Room Service', icon: Bell, color: 'bg-yellow-100 text-yellow-800' },
    { value: 'other', label: 'Other', icon: MessageSquare, color: 'bg-gray-100 text-gray-800' },
  ];

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

  const fetchRequests = async () => {
    try {
      setLoading(true);
      const params: Record<string, unknown> = {
        page: currentPage,
        limit: 20,
      };

      if (filters.status) params.status = filters.status;
      if (filters.request_type) params.request_type = filters.request_type;
      if (filters.priority) params.priority = filters.priority;
      if (filters.assigned_to) params.assigned_to = parseInt(filters.assigned_to);
      if (filters.room_id) params.room_id = parseInt(filters.room_id);

      const response = await guestRequestService.getGuestRequests(params);

      if (response.status === 'success' && response.data?.requests) {
        let filteredRequests = response.data.requests;

        // Client-side search filter
        if (filters.search) {
          const searchLower = filters.search.toLowerCase();
          filteredRequests = filteredRequests.filter(
            (req: GuestRequest) =>
              req.title?.toLowerCase().includes(searchLower) ||
              req.guest_name?.toLowerCase().includes(searchLower) ||
              req.room_number?.toString().includes(searchLower) ||
              req.description?.toLowerCase().includes(searchLower)
          );
        }

        setRequests(filteredRequests);
        setTotalPages(response.data.pagination?.total_pages || 1);
        setTotalItems(response.data.pagination?.total || 0);
      }
    } catch (error: unknown) {
      logger.error('Error fetching requests', error);
      toast.error('Failed to load guest requests');
    } finally {
      setLoading(false);
    }
  };

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

  const handleAssign = async (requestId: number, staffId?: number) => {
    try {
      setUpdatingRequestId(requestId);
      await guestRequestService.updateGuestRequest(requestId, {
        assigned_to: staffId || userInfo?.id,
        status: 'in_progress',
      });
      toast.success('Request assigned successfully');
      fetchRequests();
      if (selectedRequest?.id === requestId) {
        setSelectedRequest(null);
        setShowDetailModal(false);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to assign request');
    } finally {
      setUpdatingRequestId(null);
    }
  };

  const handleStatusChange = async (requestId: number, newStatus: string) => {
    try {
      setUpdatingRequestId(requestId);
      await guestRequestService.updateGuestRequest(requestId, {
        status: newStatus,
      });
      toast.success(`Request marked as ${newStatus.replace('_', ' ')}`);
      fetchRequests();
      if (selectedRequest?.id === requestId) {
        const updated = await guestRequestService.getGuestRequest(requestId);
        if (updated.status === 'success') {
          setSelectedRequest(updated.data);
        }
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to update request');
    } finally {
      setUpdatingRequestId(null);
    }
  };

  const handleFulfill = async (requestId: number) => {
    try {
      setUpdatingRequestId(requestId);
      await guestRequestService.fulfillRequest(requestId, staffNotes || undefined);
      toast.success('Request fulfilled successfully');
      setStaffNotes('');
      fetchRequests();
      setShowDetailModal(false);
      setSelectedRequest(null);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to fulfill request');
    } finally {
      setUpdatingRequestId(null);
    }
  };

  const handleViewDetails = async (request: GuestRequest) => {
    try {
      const response = await guestRequestService.getGuestRequest(request.id);
      if (response.status === 'success' && response.data) {
        setSelectedRequest(response.data);
        setShowDetailModal(true);
      }
    } catch (error: unknown) {
      toast.error('Failed to load request details');
    }
  };

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

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

  const getRequestTypeInfo = (type: string) => {
    return requestTypes.find(t => t.value === type) || requestTypes[requestTypes.length - 1];
  };

  const pendingCount = requests.filter(r => r.status === 'pending').length;
  const inProgressCount = requests.filter(r => r.status === 'in_progress').length;
  const urgentCount = requests.filter(r => r.priority === 'urgent' && r.status !== 'fulfilled').length;

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

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      {/* Header */}
      <div className="mb-6 sm:mb-8">
        <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
          <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-blue-400 via-indigo-500 to-purple-600 rounded-full"></div>
          <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
            Guest Request Management
          </h1>
        </div>
        <p className="text-slate-600 mt-2 sm:mt-3 text-sm sm:text-base md:text-lg font-light">
          Manage and fulfill guest service requests
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-5 md:gap-6 mb-6 sm:mb-8">
        <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 p-4 sm:p-5 border-l-4 border-l-yellow-500">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-1">Pending</p>
              <p className="text-2xl sm:text-3xl font-bold text-yellow-600">{pendingCount}</p>
            </div>
            <Clock className="w-8 h-8 sm:w-10 sm:h-10 text-yellow-500" />
          </div>
        </div>

        <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 p-4 sm:p-5 border-l-4 border-l-blue-500">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-1">In Progress</p>
              <p className="text-2xl sm:text-3xl font-bold text-blue-600">{inProgressCount}</p>
            </div>
            <RefreshCw className="w-8 h-8 sm:w-10 sm:h-10 text-blue-500" />
          </div>
        </div>

        <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 p-4 sm:p-5 border-l-4 border-l-red-500">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-1">Urgent</p>
              <p className="text-2xl sm:text-3xl font-bold text-red-600">{urgentCount}</p>
            </div>
            <AlertCircle className="w-8 h-8 sm:w-10 sm:h-10 text-red-500" />
          </div>
        </div>

        <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 p-4 sm:p-5 border-l-4 border-l-emerald-500">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-1">Total</p>
              <p className="text-2xl sm:text-3xl font-bold text-emerald-600">{totalItems}</p>
            </div>
            <Bell className="w-8 h-8 sm:w-10 sm:h-10 text-emerald-500" />
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 mb-6 sm:mb-8">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg sm:text-xl font-bold text-slate-900 flex items-center gap-2">
            <Filter className="w-5 h-5 text-blue-600" />
            Filters
          </h2>
          <button
            onClick={() => setExpandedFilters(!expandedFilters)}
            className="flex items-center gap-2 px-3 py-2 text-sm text-blue-600 hover:text-blue-700 font-medium"
          >
            {expandedFilters ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
            {expandedFilters ? 'Hide' : 'Show'} Filters
          </button>
        </div>

        {/* Search */}
        <div className="mb-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5" />
            <input
              type="text"
              placeholder="Search by guest name, room, title, or description..."
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="w-full pl-10 pr-4 py-2.5 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
            />
          </div>
        </div>

        {expandedFilters && (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">Status</label>
              <select
                value={filters.status}
                onChange={(e) => {
                  setFilters({ ...filters, status: e.target.value });
                  setCurrentPage(1);
                }}
                className="w-full px-3 py-2.5 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
              >
                <option value="">All Statuses</option>
                <option value="pending">Pending</option>
                <option value="in_progress">In Progress</option>
                <option value="fulfilled">Fulfilled</option>
                <option value="cancelled">Cancelled</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">Request Type</label>
              <select
                value={filters.request_type}
                onChange={(e) => {
                  setFilters({ ...filters, request_type: e.target.value });
                  setCurrentPage(1);
                }}
                className="w-full px-3 py-2.5 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
              >
                <option value="">All Types</option>
                {requestTypes.map((type) => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">Priority</label>
              <select
                value={filters.priority}
                onChange={(e) => {
                  setFilters({ ...filters, priority: e.target.value });
                  setCurrentPage(1);
                }}
                className="w-full px-3 py-2.5 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
              >
                <option value="">All Priorities</option>
                <option value="urgent">Urgent</option>
                <option value="high">High</option>
                <option value="normal">Normal</option>
                <option value="low">Low</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">Assigned To</label>
              <select
                value={filters.assigned_to}
                onChange={(e) => {
                  setFilters({ ...filters, assigned_to: e.target.value });
                  setCurrentPage(1);
                }}
                className="w-full px-3 py-2.5 border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700"
              >
                <option value="">All Staff</option>
                <option value="unassigned">Unassigned</option>
                {staffMembers.map((staff) => (
                  <option key={staff.id} value={staff.id}>
                    {staff.full_name}
                  </option>
                ))}
              </select>
            </div>
          </div>
        )}

        <div className="mt-4 flex gap-2">
          <button
            onClick={() => {
              setFilters({
                status: '',
                request_type: '',
                priority: '',
                assigned_to: '',
                room_id: '',
                search: '',
              });
              setCurrentPage(1);
            }}
            className="px-4 py-2 text-sm text-slate-600 hover:text-slate-800 font-medium"
          >
            Clear Filters
          </button>
          <button
            onClick={fetchRequests}
            className="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium flex items-center gap-2"
          >
            <RefreshCw className="w-4 h-4" />
            Refresh
          </button>
        </div>
      </div>

      {/* Requests List */}
      <div className="bg-white/90 backdrop-blur-md rounded-xl shadow-xl border border-slate-200/60 overflow-hidden">
        {requests.length === 0 ? (
          <div className="p-8 sm:p-12">
            <EmptyState
              title="No guest requests found"
              description="There are no guest requests matching your filters."
            />
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-slate-200">
                <thead className="bg-slate-50">
                  <tr>
                    <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                      Request
                    </th>
                    <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                      Guest / Room
                    </th>
                    <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                      Status
                    </th>
                    <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                      Priority
                    </th>
                    <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                      Assigned To
                    </th>
                    <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                      Time
                    </th>
                    <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-slate-200">
                  {requests.map((request) => {
                    const typeInfo = getRequestTypeInfo(request.request_type);
                    const TypeIcon = typeInfo.icon;

                    return (
                      <tr
                        key={request.id}
                        className={`hover:bg-slate-50 transition-colors ${
                          request.priority === 'urgent' && request.status !== 'fulfilled'
                            ? 'bg-red-50/50'
                            : ''
                        }`}
                      >
                        <td className="px-4 sm:px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center gap-3">
                            <div className={`p-2 rounded-lg ${typeInfo.color}`}>
                              <TypeIcon className="w-4 h-4" />
                            </div>
                            <div>
                              <div className="text-sm font-medium text-slate-900">{request.title}</div>
                              <div className="text-xs text-slate-500 capitalize">{typeInfo.label}</div>
                            </div>
                          </div>
                        </td>
                        <td className="px-4 sm:px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-slate-900">{request.guest_name || 'N/A'}</div>
                          <div className="text-xs text-slate-500 flex items-center gap-1">
                            <MapPin className="w-3 h-3" />
                            Room {request.room_number || request.room_id}
                          </div>
                        </td>
                        <td className="px-4 sm:px-6 py-4 whitespace-nowrap">
                          <span
                            className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full border ${getStatusColor(
                              request.status
                            )}`}
                          >
                            {request.status.replace('_', ' ')}
                          </span>
                        </td>
                        <td className="px-4 sm:px-6 py-4 whitespace-nowrap">
                          <span
                            className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full border ${getPriorityColor(
                              request.priority
                            )}`}
                          >
                            {request.priority}
                          </span>
                        </td>
                        <td className="px-4 sm:px-6 py-4 whitespace-nowrap text-sm text-slate-500">
                          {request.assigned_staff_name || (
                            <span className="text-yellow-600 font-medium">Unassigned</span>
                          )}
                        </td>
                        <td className="px-4 sm:px-6 py-4 whitespace-nowrap text-sm text-slate-500">
                          <div>{formatRelativeTime(request.requested_at)}</div>
                          {request.response_time_minutes && (
                            <div className="text-xs text-slate-400">
                              Response: {request.response_time_minutes}m
                            </div>
                          )}
                        </td>
                        <td className="px-4 sm:px-6 py-4 whitespace-nowrap text-sm font-medium">
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => handleViewDetails(request)}
                              className="text-blue-600 hover:text-blue-900 p-1.5 hover:bg-blue-50 rounded-lg transition-colors"
                              title="View details"
                            >
                              <Eye className="w-4 h-4" />
                            </button>
                            {request.status === 'pending' && !request.assigned_to && (
                              <button
                                onClick={() => handleAssign(request.id)}
                                disabled={updatingRequestId === request.id}
                                className="text-green-600 hover:text-green-900 p-1.5 hover:bg-green-50 rounded-lg transition-colors disabled:opacity-50"
                                title="Assign to me"
                              >
                                <UserCheck className="w-4 h-4" />
                              </button>
                            )}
                            {request.status === 'in_progress' && request.assigned_to === userInfo?.id && (
                              <button
                                onClick={() => handleFulfill(request.id)}
                                disabled={updatingRequestId === request.id}
                                className="text-emerald-600 hover:text-emerald-900 p-1.5 hover:bg-emerald-50 rounded-lg transition-colors disabled:opacity-50"
                                title="Mark as fulfilled"
                              >
                                <CheckCircle className="w-4 h-4" />
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            {totalPages > 1 && (
              <div className="px-4 sm:px-6 py-4 border-t border-slate-200">
                <Pagination
                  currentPage={currentPage}
                  totalPages={totalPages}
                  onPageChange={setCurrentPage}
                />
              </div>
            )}
          </>
        )}
      </div>

      {/* Detail Modal */}
      {showDetailModal && selectedRequest && (
        <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-slate-200">
              <div className="flex items-center justify-between">
                <h2 className="text-2xl font-bold text-slate-900">Request Details</h2>
                <button
                  onClick={() => {
                    setShowDetailModal(false);
                    setSelectedRequest(null);
                    setStaffNotes('');
                  }}
                  className="text-slate-400 hover:text-slate-600"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>
            </div>

            <div className="p-6 space-y-4">
              {/* Request Info */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Status</label>
                  <span
                    className={`px-3 py-1 inline-flex text-sm font-semibold rounded-full border ${getStatusColor(
                      selectedRequest.status
                    )}`}
                  >
                    {selectedRequest.status.replace('_', ' ')}
                  </span>
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Priority</label>
                  <span
                    className={`px-3 py-1 inline-flex text-sm font-semibold rounded-full border ${getPriorityColor(
                      selectedRequest.priority
                    )}`}
                  >
                    {selectedRequest.priority}
                  </span>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-500 mb-1">Title</label>
                <p className="text-slate-900 font-medium">{selectedRequest.title}</p>
              </div>

              {selectedRequest.description && (
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Description</label>
                  <p className="text-slate-900 whitespace-pre-wrap">{selectedRequest.description}</p>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Guest</label>
                  <p className="text-slate-900">{selectedRequest.guest_name || 'N/A'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Room</label>
                  <p className="text-slate-900">Room {selectedRequest.room_number || selectedRequest.room_id}</p>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Request Type</label>
                  <p className="text-slate-900 capitalize">{selectedRequest.request_type.replace('_', ' ')}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Requested At</label>
                  <p className="text-slate-900">{formatDate(selectedRequest.requested_at)}</p>
                </div>
              </div>

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

              {selectedRequest.guest_notes && (
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Guest Notes</label>
                  <p className="text-slate-900 whitespace-pre-wrap">{selectedRequest.guest_notes}</p>
                </div>
              )}

              {selectedRequest.staff_notes && (
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Staff Notes</label>
                  <p className="text-slate-900 whitespace-pre-wrap">{selectedRequest.staff_notes}</p>
                </div>
              )}

              {selectedRequest.response_time_minutes && (
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Response Time</label>
                  <p className="text-slate-900">{selectedRequest.response_time_minutes} minutes</p>
                </div>
              )}

              {selectedRequest.fulfillment_time_minutes && (
                <div>
                  <label className="block text-sm font-medium text-slate-500 mb-1">Fulfillment Time</label>
                  <p className="text-slate-900">{selectedRequest.fulfillment_time_minutes} minutes</p>
                </div>
              )}

              {/* Actions */}
              {selectedRequest.status !== 'fulfilled' && selectedRequest.status !== 'cancelled' && (
                <div className="pt-4 border-t border-slate-200 space-y-4">
                  {!selectedRequest.assigned_to && (
                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-2">Assign To</label>
                      <select
                        onChange={(e) => {
                          if (e.target.value) {
                            handleAssign(selectedRequest.id, parseInt(e.target.value));
                          }
                        }}
                        className="w-full px-3 py-2 border-2 border-slate-200 rounded-lg focus:border-blue-400 focus:ring-4 focus:ring-blue-100"
                      >
                        <option value="">Select staff member...</option>
                        <option value={userInfo?.id}>Assign to me</option>
                        {staffMembers.map((staff) => (
                          <option key={staff.id} value={staff.id}>
                            {staff.full_name}
                          </option>
                        ))}
                      </select>
                    </div>
                  )}

                  {selectedRequest.status === 'in_progress' && selectedRequest.assigned_to === userInfo?.id && (
                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-2">Staff Notes (Optional)</label>
                      <textarea
                        value={staffNotes}
                        onChange={(e) => setStaffNotes(e.target.value)}
                        rows={3}
                        placeholder="Add notes about fulfillment..."
                        className="w-full px-3 py-2 border-2 border-slate-200 rounded-lg focus:border-blue-400 focus:ring-4 focus:ring-blue-100"
                      />
                      <button
                        onClick={() => handleFulfill(selectedRequest.id)}
                        disabled={updatingRequestId === selectedRequest.id}
                        className="mt-2 w-full px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 font-medium disabled:opacity-50"
                      >
                        {updatingRequestId === selectedRequest.id ? 'Fulfilling...' : 'Mark as Fulfilled'}
                      </button>
                    </div>
                  )}

                  {selectedRequest.status === 'pending' && selectedRequest.assigned_to && (
                    <button
                      onClick={() => handleStatusChange(selectedRequest.id, 'in_progress')}
                      disabled={updatingRequestId === selectedRequest.id}
                      className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium disabled:opacity-50"
                    >
                      Start Working
                    </button>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default GuestRequestManagementPage;

