
import React, { useMemo, useEffect, useState, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { ResourceType, User, Resource } from '../types';
import { useResources, useCreateResource, useUpdateResource } from '../hooks/useResources';
import { useAppointments } from '../hooks/useAppointments';
import { useStaff, StaffMember } from '../hooks/useStaff';
import ResourceCalendar from '../components/ResourceCalendar';
import ResourceDetailModal from '../components/ResourceDetailModal';
import Portal from '../components/Portal';
import { getOverQuotaResourceIds } from '../utils/quotaUtils';
import { LocationSelector, useShouldShowLocationSelector, useAutoSelectLocation } from '../components/LocationSelector';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
import {
  Plus,
  User as UserIcon,
  Home,
  Wrench,
  Eye,
  Calendar,
  Settings,
  X,
  Pencil,
  AlertTriangle,
  MapPin,
  Truck
} from 'lucide-react';

const ResourceIcon: React.FC<{ type: ResourceType }> = ({ type }) => {
  switch (type) {
    case 'STAFF':
      return <UserIcon size={16} className="text-blue-500" />;
    case 'ROOM':
      return <Home size={16} className="text-green-500" />;
    case 'EQUIPMENT':
      return <Wrench size={16} className="text-purple-500" />;
    default:
      return null;
  }
};

interface ResourcesProps {
  onMasquerade: (user: User) => void;
  effectiveUser: User;
}

const Resources: React.FC<ResourcesProps> = ({ onMasquerade, effectiveUser }) => {
  const { t } = useTranslation();
  // All hooks must be called at the top, before any conditional returns
  const { data: resources = [], isLoading, error } = useResources();
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [editingResource, setEditingResource] = React.useState<Resource | null>(null);
  const [calendarResource, setCalendarResource] = React.useState<{ id: string; name: string } | null>(null);
  const [detailResource, setDetailResource] = React.useState<Resource | null>(null);

  // Calculate over-quota resources (will be auto-archived when grace period ends)
  const overQuotaResourceIds = useMemo(
    () => getOverQuotaResourceIds(resources, effectiveUser.quota_overages),
    [resources, effectiveUser.quota_overages]
  );

  // Form state
  const [formType, setFormType] = React.useState<ResourceType>('STAFF');
  const [formName, setFormName] = React.useState('');
  const [formDescription, setFormDescription] = React.useState('');
  const [formMaxConcurrent, setFormMaxConcurrent] = React.useState(1);
  const [formMultilaneEnabled, setFormMultilaneEnabled] = React.useState(false);
  const [formSavedLaneCount, setFormSavedLaneCount] = React.useState<number | undefined>(undefined);
  const [formUserCanEditSchedule, setFormUserCanEditSchedule] = React.useState(false);
  const [formLocationId, setFormLocationId] = React.useState<number | null>(null);
  const [formIsMobile, setFormIsMobile] = React.useState(false);

  // Location features
  const { canUse } = usePlanFeatures();
  const hasMultiLocation = canUse('multi_location');
  const showLocationSelector = useShouldShowLocationSelector();

  // Auto-select location when only one exists
  useAutoSelectLocation(formLocationId, setFormLocationId);

  // Staff selection state
  const [selectedStaffId, setSelectedStaffId] = useState<string | null>(null);
  const [staffSearchQuery, setStaffSearchQuery] = useState('');
  const [debouncedSearchQuery, setDebouncedSearchQuery] = useState('');
  const [showStaffDropdown, setShowStaffDropdown] = useState(false);
  const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
  const staffInputRef = useRef<HTMLInputElement>(null);
  const staffDropdownRef = useRef<HTMLDivElement>(null);

  // Debounce search query for API calls
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchQuery(staffSearchQuery);
    }, 300);
    return () => clearTimeout(timer);
  }, [staffSearchQuery]);

  // Fetch staff members for autocomplete (using debounced query)
  const { data: staffMembers = [] } = useStaff({ search: debouncedSearchQuery });

  // Filter staff members based on search query (client-side filtering for immediate feedback)
  const filteredStaff = useMemo(() => {
    // Always show all staff when dropdown is open and no search query
    if (!staffSearchQuery.trim()) return staffMembers;

    const query = staffSearchQuery.toLowerCase().trim();
    return staffMembers.filter(
      (s) => s.name.toLowerCase().includes(query) || s.email.toLowerCase().includes(query)
    );
  }, [staffMembers, staffSearchQuery]);

  // Get selected staff member details
  const selectedStaff = useMemo(() => {
    return staffMembers.find((s) => s.id === selectedStaffId) || null;
  }, [staffMembers, selectedStaffId]);

  // Get the list that's currently displayed in the dropdown
  const displayedStaff = useMemo(() => {
    return staffSearchQuery.trim() === '' ? staffMembers : filteredStaff;
  }, [staffSearchQuery, staffMembers, filteredStaff]);

  // Reset highlighted index when filtered staff changes
  useEffect(() => {
    setHighlightedIndex(-1);
  }, [filteredStaff]);

  // Handle keyboard navigation
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (!showStaffDropdown || displayedStaff.length === 0) return;

    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setHighlightedIndex((prev) =>
          prev < displayedStaff.length - 1 ? prev + 1 : prev
        );
        break;
      case 'ArrowUp':
        e.preventDefault();
        setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : -1));
        break;
      case 'Enter':
        e.preventDefault();
        if (highlightedIndex >= 0 && highlightedIndex < displayedStaff.length) {
          const staff = displayedStaff[highlightedIndex];
          setSelectedStaffId(staff.id);
          setStaffSearchQuery(staff.name);
          setShowStaffDropdown(false);
          setHighlightedIndex(-1);
        }
        break;
      case 'Escape':
        e.preventDefault();
        setShowStaffDropdown(false);
        setHighlightedIndex(-1);
        break;
    }
  };

  // Scroll highlighted item into view
  useEffect(() => {
    if (highlightedIndex >= 0 && staffDropdownRef.current) {
      const highlightedElement = staffDropdownRef.current.children[highlightedIndex] as HTMLElement;
      if (highlightedElement) {
        highlightedElement.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
      }
    }
  }, [highlightedIndex]);

  const createResourceMutation = useCreateResource();
  const updateResourceMutation = useUpdateResource();

  // Fetch ALL appointments (not filtered by date) to count per resource
  // We filter client-side for future appointments
  const { data: allAppointments = [] } = useAppointments();

  // Count future appointments per resource
  const appointmentCountByResource = useMemo(() => {
    const counts: Record<string, number> = {};
    const now = new Date();
    allAppointments.forEach(apt => {
      // Only count future appointments that have a resource assigned
      if (apt.resourceId && new Date(apt.startTime) >= now) {
        counts[apt.resourceId] = (counts[apt.resourceId] || 0) + 1;
      }
    });
    return counts;
  }, [allAppointments]);

  // Reset form when modal opens/closes or editing resource changes
  // NOTE: Only depend on editingResource and isModalOpen, NOT staffMembers
  // to avoid clearing the form when staff data updates during search
  useEffect(() => {
    if (editingResource) {
      setFormType(editingResource.type);
      setFormName(editingResource.name);
      setFormDescription(''); // TODO: Add description to Resource type when backend supports it
      setFormMaxConcurrent(editingResource.maxConcurrentEvents);
      setFormMultilaneEnabled(editingResource.maxConcurrentEvents > 1);
      setFormSavedLaneCount(editingResource.savedLaneCount);
      setFormUserCanEditSchedule(editingResource.userCanEditSchedule ?? false);
      setFormLocationId(editingResource.locationId ?? null);
      setFormIsMobile(editingResource.isMobile ?? false);
      // Pre-fill staff if editing a STAFF resource
      if (editingResource.type === 'STAFF' && editingResource.userId) {
        setSelectedStaffId(editingResource.userId);
        // We'll set the staff name in a separate effect
      } else {
        setSelectedStaffId(null);
        setStaffSearchQuery('');
      }
    } else if (isModalOpen) {
      // Only reset when creating new (modal opened without editing resource)
      setFormType('STAFF');
      setFormName('');
      setFormDescription('');
      setFormMaxConcurrent(1);
      setFormMultilaneEnabled(false);
      setFormSavedLaneCount(undefined);
      setFormUserCanEditSchedule(false);
      setFormLocationId(null);
      setFormIsMobile(false);
      setSelectedStaffId(null);
      setStaffSearchQuery('');
      setDebouncedSearchQuery('');
    }
  }, [editingResource, isModalOpen]);

  // Separate effect to populate staff name when editing
  // This runs when staffMembers loads and we have a selected staff ID
  useEffect(() => {
    if (editingResource && editingResource.type === 'STAFF' && editingResource.userId && selectedStaffId === editingResource.userId) {
      const staff = staffMembers.find(s => s.id === editingResource.userId);
      if (staff && !staffSearchQuery) {
        // Only set if not already set to avoid overwriting user input
        setStaffSearchQuery(staff.name);
      }
    }
  }, [staffMembers, editingResource, selectedStaffId, staffSearchQuery]);

  const openCreateModal = () => {
    setIsModalOpen(true);
    setEditingResource(null);
  };

  const openEditModal = (resource: Resource) => {
    setEditingResource(resource);
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setEditingResource(null);
    setIsModalOpen(false);
  };

  const handleMultilaneToggle = (enabled: boolean) => {
    setFormMultilaneEnabled(enabled);
    if (enabled) {
      // Restore saved lane count or default to 2
      setFormMaxConcurrent(formSavedLaneCount ?? 2);
    } else {
      // Save current lane count before disabling
      if (formMaxConcurrent > 1) {
        setFormSavedLaneCount(formMaxConcurrent);
      }
      setFormMaxConcurrent(1);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (formType === 'STAFF' && !selectedStaffId) {
      alert(t('resources.staffRequired')); // Basic alert for now
      return;
    }

    const resourceData: {
      name: string;
      type: ResourceType;
      maxConcurrentEvents: number;
      savedLaneCount: number | undefined;
      userId?: string;
      userCanEditSchedule?: boolean;
      locationId?: number | null;
      isMobile?: boolean;
    } = {
      name: formName,
      type: formType,
      maxConcurrentEvents: formMaxConcurrent,
      savedLaneCount: formMultilaneEnabled ? undefined : formSavedLaneCount,
    };

    if (formType === 'STAFF' && selectedStaffId) {
      resourceData.userId = selectedStaffId;
      resourceData.userCanEditSchedule = formUserCanEditSchedule;
    }

    // Add location fields if multi-location is enabled
    if (hasMultiLocation) {
      resourceData.locationId = formIsMobile ? null : formLocationId;
      resourceData.isMobile = formIsMobile;
    }

    if (editingResource) {
      updateResourceMutation.mutate({
        id: editingResource.id,
        updates: resourceData
      }, {
        onSuccess: closeModal
      });
    } else {
      createResourceMutation.mutate(resourceData, {
        onSuccess: closeModal
      });
    }
  };

  if (isLoading) {
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <p className="text-red-800 dark:text-red-300">{t('resources.errorLoading')}: {(error as Error).message}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-8 max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{t('resources.title')}</h2>
          <p className="text-gray-500 dark:text-gray-400">{t('resources.description')}</p>
        </div>
        <button
          onClick={openCreateModal}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors shadow-sm font-medium"
        >
          <Plus size={18} />
          {t('resources.addResource')}
        </button>
      </div>

      {/* Table */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden transition-colors duration-200">
        <div className="overflow-x-auto">
          <table className="w-full text-sm text-left">
            <thead className="text-xs text-gray-500 dark:text-gray-400 uppercase bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700">
              <tr>
                <th className="px-6 py-4 font-medium">{t('resources.resourceName')}</th>
                <th className="px-6 py-4 font-medium">{t('resources.type')}</th>
                <th className="px-6 py-4 font-medium">{t('resources.upcoming')}</th>
                <th className="px-6 py-4 font-medium">{t('resources.capacity')}</th>
                <th className="px-6 py-4 font-medium">{t('scheduler.status')}</th>
                <th className="px-6 py-4 font-medium text-right">{t('common.actions')}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
              {resources.map((resource: Resource) => {
                const isOverQuota = overQuotaResourceIds.has(resource.id);
                return (
                  <tr
                    key={resource.id}
                    className={`transition-colors group ${
                      isOverQuota
                        ? 'bg-amber-50/50 dark:bg-amber-900/10 opacity-70'
                        : 'hover:bg-gray-50 dark:hover:bg-gray-700/30'
                    }`}
                    title={isOverQuota ? 'Over quota - will be archived if not resolved' : undefined}
                  >
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className={`w-8 h-8 rounded-lg flex items-center justify-center overflow-hidden border ${
                          isOverQuota
                            ? 'bg-amber-100 dark:bg-amber-800/50 border-amber-300 dark:border-amber-600'
                            : 'bg-gray-100 dark:bg-gray-700 border-gray-200 dark:border-gray-600'
                        }`}>
                          {isOverQuota ? <AlertTriangle size={16} className="text-amber-600 dark:text-amber-400" /> : <ResourceIcon type={resource.type} />}
                        </div>
                        <div>
                          <div className={`font-medium ${isOverQuota ? 'text-amber-800 dark:text-amber-300' : 'text-gray-900 dark:text-white'}`}>
                            {resource.name}
                            {isOverQuota && (
                              <span className="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-amber-100 text-amber-700 dark:bg-amber-800/50 dark:text-amber-400">
                                Over quota
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize ${resource.type === 'STAFF' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300' :
                        resource.type === 'ROOM' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
                          'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300'
                        }`}>
                        {resource.type.toLowerCase()}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-1.5 text-gray-600 dark:text-gray-300">
                        <Calendar size={14} className="text-brand-500" />
                        <span className="font-medium">{appointmentCountByResource[String(resource.id)] || 0}</span>
                        <span className="text-xs text-gray-400">{t('resources.appointments')}</span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                        resource.maxConcurrentEvents > 1
                          ? 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300'
                          : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
                      }`}>
                        {resource.maxConcurrentEvents > 1
                          ? `${resource.maxConcurrentEvents} ${t('resources.simultaneous')}`
                          : `1 ${t('resources.atATime')}`
                        }
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      {isOverQuota ? (
                        <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400">
                          <AlertTriangle size={12} />
                          Over Quota
                        </span>
                      ) : (
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">
                          {t('resources.active')}
                        </span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-2">
                        {resource.type === 'STAFF' && resource.userId && (
                          <button
                            onClick={() => setDetailResource(resource)}
                            className="text-green-600 hover:text-green-500 dark:text-green-400 dark:hover:text-green-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-green-200 dark:border-green-800 rounded-lg hover:bg-green-50 dark:hover:bg-green-900/30 transition-colors"
                            title={t('resources.trackLocation', 'Track Location')}
                          >
                            <MapPin size={14} /> {t('resources.trackLocation', 'Track')}
                          </button>
                        )}
                        <button
                          onClick={() => setCalendarResource({ id: resource.id, name: resource.name })}
                          className="text-brand-600 hover:text-brand-500 dark:text-brand-400 dark:hover:text-brand-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-brand-200 dark:border-brand-800 rounded-lg hover:bg-brand-50 dark:hover:bg-brand-900/30 transition-colors"
                          title={`${t('resources.viewCalendar')} - ${resource.name}`}
                        >
                          <Eye size={14} /> {t('resources.viewCalendar')}
                        </button>
                        <button
                          onClick={() => openEditModal(resource)}
                          className="p-1.5 text-gray-400 hover:text-brand-600 dark:hover:text-brand-400 transition-colors"
                          title={t('common.edit', 'Edit')}
                        >
                          <Pencil size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {resources.length === 0 && (
            <div className="p-12 text-center">
              <p className="text-gray-500 dark:text-gray-400">{t('resources.noResourcesFound')}</p>
            </div>
          )}
        </div>
      </div>

      {/* Create/Edit Resource Modal */}
      {isModalOpen && (
        <Portal>
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <div key={editingResource?.id || 'new'} className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md overflow-hidden">
              <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                  {editingResource ? t('resources.editResource') : t('resources.addNewResource')}
                </h3>
                <button onClick={closeModal} className="text-gray-400 hover:text-gray-500 dark:hover:text-gray-300">
                  <span className="sr-only">{t('common.close')}</span>
                  <X size={24} />
                </button>
              </div>
              <form onSubmit={handleSubmit} className="p-6 space-y-4">
                {/* Resource Type */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('resources.resourceType')} <span className="text-red-500">*</span>
                  </label>
                  <select
                    value={formType}
                    onChange={(e) => {
                      setFormType(e.target.value as ResourceType);
                      setSelectedStaffId(null); // Clear staff selection if type changes
                      setStaffSearchQuery('');
                      setDebouncedSearchQuery('');
                      setShowStaffDropdown(false);
                      setHighlightedIndex(-1);
                    }}
                    className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                    required
                  >
                    <option value="STAFF">{t('resources.staffMember')}</option>
                    <option value="ROOM">{t('resources.room')}</option>
                    <option value="EQUIPMENT">{t('resources.equipment')}</option>
                  </select>
                </div>

                {/* Staff Member Selector (Conditional) */}
                {formType === 'STAFF' && (
                  <div className="relative">
                    <label htmlFor="staff-member" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      {t('resources.assignStaff')} <span className="text-red-500">*</span>
                    </label>
                    <input
                      id="staff-member"
                      type="text"
                      ref={staffInputRef}
                      value={staffSearchQuery}
                      onChange={(e) => {
                        setStaffSearchQuery(e.target.value);
                        setShowStaffDropdown(true);
                        setHighlightedIndex(-1);
                        // Clear selection when user types
                        if (selectedStaffId) {
                          setSelectedStaffId(null);
                        }
                      }}
                      onKeyDown={handleKeyDown}
                      onFocus={() => {
                        setShowStaffDropdown(true);
                        setHighlightedIndex(-1);
                      }}
                      onBlur={() => {
                        // Delay to allow click on dropdown
                        setTimeout(() => {
                          setShowStaffDropdown(false);
                          setHighlightedIndex(-1);
                        }, 200);
                      }}
                      className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 focus:bg-white dark:focus:bg-gray-600"
                      placeholder={t('resources.searchStaffPlaceholder')}
                      required={formType === 'STAFF'}
                      autoComplete="off"
                      aria-autocomplete="list"
                      aria-controls="staff-suggestions"
                      aria-expanded={showStaffDropdown}
                      aria-activedescendant={highlightedIndex >= 0 ? `staff-option-${highlightedIndex}` : undefined}
                    />
                    {showStaffDropdown && displayedStaff.length > 0 && (
                      <div
                        ref={staffDropdownRef}
                        id="staff-suggestions"
                        className="absolute z-10 mt-1 w-full bg-white dark:bg-gray-700 shadow-lg rounded-md border border-gray-200 dark:border-gray-600 max-h-60 overflow-auto"
                        role="listbox"
                      >
                        {displayedStaff.map((staff, index) => (
                          <div
                            key={staff.id}
                            id={`staff-option-${index}`}
                            className={`p-2 text-sm text-gray-900 dark:text-white cursor-pointer transition-colors ${
                              index === highlightedIndex
                                ? 'bg-brand-100 dark:bg-brand-900/50'
                                : selectedStaffId === staff.id
                                ? 'bg-brand-50 dark:bg-brand-900/30'
                                : 'hover:bg-gray-50 dark:hover:bg-gray-600'
                            }`}
                            onClick={() => {
                              setSelectedStaffId(staff.id);
                              setStaffSearchQuery(staff.name);
                              setShowStaffDropdown(false);
                              setHighlightedIndex(-1);
                            }}
                            onMouseEnter={() => setHighlightedIndex(index)}
                            onMouseDown={(e) => {
                              // Prevent input blur on mousedown
                              e.preventDefault();
                            }}
                            role="option"
                            aria-selected={selectedStaffId === staff.id}
                          >
                            <div className="font-medium">{staff.name}</div>
                            <div className="text-xs text-gray-500 dark:text-gray-400">{staff.email}</div>
                          </div>
                        ))}
                      </div>
                    )}
                    {formType === 'STAFF' && !selectedStaffId && staffSearchQuery.trim() !== '' && filteredStaff.length === 0 && (
                      <p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
                        {t('resources.noMatchingStaff')}
                      </p>
                    )}
                    {selectedStaffId && selectedStaff && (
                      <p className="mt-1 text-xs text-green-600 dark:text-green-400 flex items-center gap-1">
                        <span className="inline-block w-2 h-2 bg-green-500 rounded-full"></span>
                        Selected: {selectedStaff.name}
                      </p>
                    )}
                  </div>
                )}

                {/* Resource Name */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('resources.resourceName')}
                  </label>
                  <input
                    type="text"
                    value={formName}
                    onChange={(e) => setFormName(e.target.value)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 focus:bg-white dark:focus:bg-gray-600"
                    placeholder={formType === 'STAFF' ? 'e.g. Sarah (Stylist)' : formType === 'ROOM' ? 'e.g. Massage Room 1' : 'e.g. Laser Machine'}
                    required
                  />
                </div>

                {/* Location Selection - only shown when multi-location is enabled and >1 locations */}
                {hasMultiLocation && showLocationSelector && (
                  <>
                    {/* Mobile Resource Toggle (for STAFF type) */}
                    {formType === 'STAFF' && (
                      <div className="flex items-center justify-between py-2">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                            {t('resources.mobileResource', 'Mobile Resource')}
                          </label>
                          <p className="text-xs text-gray-500 dark:text-gray-400">
                            {t('resources.mobileResourceDescription', 'Can work at any location (e.g., mobile technician, field service)')}
                          </p>
                        </div>
                        <button
                          type="button"
                          onClick={() => setFormIsMobile(!formIsMobile)}
                          className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 ${
                            formIsMobile ? 'bg-brand-600' : 'bg-gray-200 dark:bg-gray-600'
                          }`}
                          role="switch"
                          aria-checked={formIsMobile}
                        >
                          <span
                            className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                              formIsMobile ? 'translate-x-5' : 'translate-x-0'
                            }`}
                          />
                        </button>
                      </div>
                    )}

                    {/* Location Selector - hidden for mobile resources */}
                    {!formIsMobile && (
                      <LocationSelector
                        value={formLocationId}
                        onChange={setFormLocationId}
                        label={t('resources.location', 'Location')}
                        required={!formIsMobile}
                        forceShow={true}
                      />
                    )}

                    {formIsMobile && (
                      <div className="flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
                        <Truck size={18} className="text-blue-600 dark:text-blue-400" />
                        <span className="text-sm text-blue-700 dark:text-blue-300">
                          {t('resources.mobileResourceHint', 'This resource can serve customers at any location')}
                        </span>
                      </div>
                    )}
                  </>
                )}

                {/* Description */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('resources.resourceDescription')}
                  </label>
                  <textarea
                    value={formDescription}
                    onChange={(e) => setFormDescription(e.target.value)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 focus:bg-white dark:focus:bg-gray-600"
                    placeholder={t('resources.descriptionPlaceholder')}
                    rows={2}
                  />
                </div>

                {/* Multilane Toggle */}
                <div className="flex items-center justify-between py-2">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                      {t('resources.multilaneMode')}
                    </label>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      {t('resources.multilaneDescription')}
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={() => handleMultilaneToggle(!formMultilaneEnabled)}
                    className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 ${
                      formMultilaneEnabled ? 'bg-brand-600' : 'bg-gray-200 dark:bg-gray-600'
                    }`}
                    role="switch"
                    aria-checked={formMultilaneEnabled}
                  >
                    <span
                      className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                        formMultilaneEnabled ? 'translate-x-5' : 'translate-x-0'
                      }`}
                    />
                  </button>
                </div>

                {/* Number of Lanes (only shown when multilane is enabled) */}
                {formMultilaneEnabled && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      {t('resources.numberOfLanes')}
                    </label>
                    <input
                      type="number"
                      min={2}
                      max={10}
                      value={formMaxConcurrent}
                      onChange={(e) => setFormMaxConcurrent(Math.max(2, parseInt(e.target.value) || 2))}
                      className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 focus:bg-white dark:focus:bg-gray-600"
                    />
                    <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      {t('resources.lanesHelp')}
                    </p>
                  </div>
                )}

                {/* Allow User to Edit Schedule Toggle (only for STAFF type) */}
                {formType === 'STAFF' && selectedStaffId && (
                  <div className="flex items-center justify-between py-2">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                        {t('resources.allowEditSchedule', 'Allow User to Edit Schedule')}
                      </label>
                      <p className="text-xs text-gray-500 dark:text-gray-400">
                        {t('resources.allowEditScheduleDescription', 'Let this staff member reschedule and resize their own appointments in the mobile app')}
                      </p>
                    </div>
                    <button
                      type="button"
                      onClick={() => setFormUserCanEditSchedule(!formUserCanEditSchedule)}
                      className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 ${
                        formUserCanEditSchedule ? 'bg-brand-600' : 'bg-gray-200 dark:bg-gray-600'
                      }`}
                      role="switch"
                      aria-checked={formUserCanEditSchedule}
                    >
                      <span
                        className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                          formUserCanEditSchedule ? 'translate-x-5' : 'translate-x-0'
                        }`}
                      />
                    </button>
                  </div>
                )}

                {/* Submit Buttons */}
                <div className="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
                  <button
                    type="button"
                    onClick={closeModal}
                    className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600"
                  >
                    {t('common.cancel')}
                  </button>
                  <button
                    type="submit"
                    disabled={createResourceMutation.isPending || updateResourceMutation.isPending}
                    className="px-4 py-2 text-sm font-medium text-white bg-brand-600 rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {createResourceMutation.isPending || updateResourceMutation.isPending
                      ? t('common.saving')
                      : editingResource
                        ? t('resources.updateResource')
                        : t('resources.createResource')
                    }
                  </button>
                </div>
              </form>
            </div>
          </div>
        </Portal>
      )}

      {/* Resource Calendar Modal */}
      {calendarResource && (
        <ResourceCalendar
          resourceId={calendarResource.id}
          resourceName={calendarResource.name}
          onClose={() => setCalendarResource(null)}
        />
      )}

      {/* Resource Detail Modal (with location tracking) */}
      {detailResource && (
        <ResourceDetailModal
          resource={detailResource}
          onClose={() => setDetailResource(null)}
        />
      )}
    </div>
  );
};

export default Resources;
