import { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { VIP } from '@/types';
import { Plus, Edit, Trash2, Search, X, Calendar, Filter, ArrowUpDown } from 'lucide-react';
import { VIPForm, VIPFormData } from '@/components/VIPForm';
import { VIPCardSkeleton, TableSkeleton } from '@/components/Skeleton';
import { FilterModal } from '@/components/FilterModal';
import { FilterChip } from '@/components/FilterChip';
import { useDebounce } from '@/hooks/useDebounce';

export function VIPList() {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const [showForm, setShowForm] = useState(false);
  const [editingVIP, setEditingVIP] = useState<VIP | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Search and filter state
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedDepartments, setSelectedDepartments] = useState<string[]>([]);
  const [selectedArrivalModes, setSelectedArrivalModes] = useState<string[]>([]);
  const [filterModalOpen, setFilterModalOpen] = useState(false);

  // Sort state
  const [sortColumn, setSortColumn] = useState<'name' | 'organization' | 'department' | 'arrivalMode'>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');

  // Debounce search term for better performance
  const debouncedSearchTerm = useDebounce(searchTerm, 300);

  const { data: vips, isLoading } = useQuery<VIP[]>({
    queryKey: ['vips'],
    queryFn: async () => {
      const { data } = await api.get('/vips');
      return data;
    },
  });

  const createMutation = useMutation({
    mutationFn: async (data: VIPFormData) => {
      await api.post('/vips', data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vips'] });
      setShowForm(false);
      setIsSubmitting(false);
      toast.success('VIP created successfully');
    },
    onError: (error: any) => {
      console.error('[VIP] Failed to create:', error);
      setIsSubmitting(false);
      toast.error(error.response?.data?.message || 'Failed to create VIP');
    },
  });

  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: VIPFormData }) => {
      await api.patch(`/vips/${id}`, data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vips'] });
      setShowForm(false);
      setEditingVIP(null);
      setIsSubmitting(false);
      toast.success('VIP updated successfully');
    },
    onError: (error: any) => {
      console.error('[VIP] Failed to update:', error);
      setIsSubmitting(false);
      toast.error(error.response?.data?.message || 'Failed to update VIP');
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      await api.delete(`/vips/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vips'] });
      toast.success('VIP deleted successfully');
    },
    onError: (error: any) => {
      console.error('[VIP] Failed to delete:', error);
      toast.error(error.response?.data?.message || 'Failed to delete VIP');
    },
  });

  // Helper to extract last name from full name
  const getLastName = (fullName: string): string => {
    const parts = fullName.trim().split(/\s+/);
    return parts[parts.length - 1].toLowerCase();
  };

  // Filter and sort VIPs based on search and filters
  const filteredVIPs = useMemo(() => {
    if (!vips) return [];

    // First filter
    let filtered = vips.filter((vip) => {
      // Search by name (using debounced term)
      const matchesSearch = debouncedSearchTerm === '' ||
        vip.name.toLowerCase().includes(debouncedSearchTerm.toLowerCase());

      // Filter by department
      const matchesDepartment = selectedDepartments.length === 0 ||
        selectedDepartments.includes(vip.department);

      // Filter by arrival mode
      const matchesArrivalMode = selectedArrivalModes.length === 0 ||
        selectedArrivalModes.includes(vip.arrivalMode);

      return matchesSearch && matchesDepartment && matchesArrivalMode;
    });

    // Then sort
    filtered.sort((a, b) => {
      let aValue: string;
      let bValue: string;

      // Special handling for name column - sort by last name
      if (sortColumn === 'name') {
        aValue = getLastName(a.name);
        bValue = getLastName(b.name);
      } else {
        aValue = (a[sortColumn] || '').toString().toLowerCase();
        bValue = (b[sortColumn] || '').toString().toLowerCase();
      }

      if (aValue < bValue) return sortDirection === 'asc' ? -1 : 1;
      if (aValue > bValue) return sortDirection === 'asc' ? 1 : -1;
      return 0;
    });

    return filtered;
  }, [vips, debouncedSearchTerm, selectedDepartments, selectedArrivalModes, sortColumn, sortDirection]);

  const handleDepartmentToggle = (department: string) => {
    setSelectedDepartments((prev) =>
      prev.includes(department)
        ? prev.filter((d) => d !== department)
        : [...prev, department]
    );
  };

  const handleArrivalModeToggle = (mode: string) => {
    setSelectedArrivalModes((prev) =>
      prev.includes(mode)
        ? prev.filter((m) => m !== mode)
        : [...prev, mode]
    );
  };

  const handleClearFilters = () => {
    setSearchTerm('');
    setSelectedDepartments([]);
    setSelectedArrivalModes([]);
  };

  const handleSort = (column: typeof sortColumn) => {
    if (sortColumn === column) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortColumn(column);
      setSortDirection('asc');
    }
  };

  const handleRemoveDepartmentFilter = (dept: string) => {
    setSelectedDepartments((prev) => prev.filter((d) => d !== dept));
  };

  const handleRemoveArrivalModeFilter = (mode: string) => {
    setSelectedArrivalModes((prev) => prev.filter((m) => m !== mode));
  };

  const getFilterLabel = (value: string, type: 'department' | 'arrivalMode') => {
    const labels = {
      department: {
        'OFFICE_OF_DEVELOPMENT': 'Office of Development',
        'ADMIN': 'Admin',
      },
      arrivalMode: {
        'FLIGHT': 'Flight',
        'SELF_DRIVING': 'Self Driving',
      },
    };
    return labels[type][value as keyof typeof labels[typeof type]] || value;
  };

  const handleAdd = () => {
    setEditingVIP(null);
    setShowForm(true);
  };

  const handleEdit = (vip: VIP) => {
    setEditingVIP(vip);
    setShowForm(true);
  };

  const handleDelete = (id: string, name: string) => {
    if (confirm(`Delete VIP "${name}"? This action cannot be undone.`)) {
      deleteMutation.mutate(id);
    }
  };

  const handleSubmit = (data: VIPFormData) => {
    setIsSubmitting(true);
    if (editingVIP) {
      updateMutation.mutate({ id: editingVIP.id, data });
    } else {
      createMutation.mutate(data);
    }
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingVIP(null);
    setIsSubmitting(false);
  };

  if (isLoading) {
    return (
      <div>
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
          <h1 className="text-2xl sm:text-3xl font-bold text-foreground">VIPs</h1>
          <button
            disabled
            className="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary/50 cursor-not-allowed"
            style={{ minHeight: '44px' }}
          >
            <Plus className="h-5 w-5 mr-2" />
            Add VIP
          </button>
        </div>
        <div className="hidden lg:block">
          <TableSkeleton rows={8} />
        </div>
        <div className="lg:hidden">
          <VIPCardSkeleton cards={5} />
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <h1 className="text-2xl sm:text-3xl font-bold text-foreground">VIPs</h1>
        <button
          onClick={handleAdd}
          className="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90 transition-colors"
          style={{ minHeight: '44px' }}
        >
          <Plus className="h-5 w-5 mr-2" />
          Add VIP
        </button>
      </div>

      {/* Search and Filter Section */}
      <div className="bg-card shadow-soft border border-border rounded-lg p-4 mb-6">
        <div className="flex gap-3">
          {/* Search */}
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-muted-foreground pointer-events-none" />
            <input
              type="text"
              placeholder="Search by name..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 border border-input rounded-md focus:ring-ring focus:border-ring text-base bg-background text-foreground transition-colors"
              style={{ minHeight: '44px' }}
            />
          </div>

          {/* Filter Button */}
          <button
            onClick={() => setFilterModalOpen(true)}
            className="inline-flex items-center px-4 py-2 border border-input rounded-md text-foreground bg-background hover:bg-accent font-medium transition-colors"
            style={{ minHeight: '44px' }}
          >
            <Filter className="h-5 w-5 mr-2" />
            Filters
            {(selectedDepartments.length > 0 || selectedArrivalModes.length > 0) && (
              <span className="ml-2 inline-flex items-center justify-center px-2 py-0.5 text-xs font-bold leading-none text-white bg-primary rounded-full">
                {selectedDepartments.length + selectedArrivalModes.length}
              </span>
            )}
          </button>
        </div>

        {/* Active Filter Chips */}
        {(selectedDepartments.length > 0 || selectedArrivalModes.length > 0) && (
          <div className="flex flex-wrap gap-2 mt-3 pt-3 border-t border-border">
            <span className="text-sm text-muted-foreground py-1.5">Active filters:</span>
            {selectedDepartments.map((dept) => (
              <FilterChip
                key={dept}
                label={getFilterLabel(dept, 'department')}
                onRemove={() => handleRemoveDepartmentFilter(dept)}
              />
            ))}
            {selectedArrivalModes.map((mode) => (
              <FilterChip
                key={mode}
                label={getFilterLabel(mode, 'arrivalMode')}
                onRemove={() => handleRemoveArrivalModeFilter(mode)}
              />
            ))}
          </div>
        )}

        {/* Results count */}
        <div className="flex items-center justify-between mt-3 pt-3 border-t border-border">
          <div className="text-sm text-muted-foreground">
            Showing <span className="font-medium text-foreground">{filteredVIPs.length}</span> of <span className="font-medium text-foreground">{vips?.length || 0}</span> VIPs
            {debouncedSearchTerm !== searchTerm && <span className="ml-2 text-muted-foreground/70">(searching...)</span>}
          </div>
          {(searchTerm || selectedDepartments.length > 0 || selectedArrivalModes.length > 0) && (
            <button
              onClick={handleClearFilters}
              className="inline-flex items-center px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground hover:bg-accent rounded-md transition-colors"
            >
              <X className="h-4 w-4 mr-1" />
              Clear All
            </button>
          )}
        </div>
      </div>

      {/* Desktop Table View - shows on large screens */}
      <div className="hidden lg:block bg-card shadow-soft border border-border rounded-lg overflow-hidden">
        <table className="min-w-full divide-y divide-border">
          <thead className="bg-muted/30">
            <tr>
              <th
                className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider cursor-pointer hover:bg-accent transition-colors"
                onClick={() => handleSort('name')}
              >
                <div className="flex items-center gap-2">
                  Name
                  <ArrowUpDown className="h-4 w-4" />
                  {sortColumn === 'name' && <span className="text-primary">{sortDirection === 'asc' ? '↑' : '↓'}</span>}
                </div>
              </th>
              <th
                className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider cursor-pointer hover:bg-accent transition-colors"
                onClick={() => handleSort('organization')}
              >
                <div className="flex items-center gap-2">
                  Organization
                  <ArrowUpDown className="h-4 w-4" />
                  {sortColumn === 'organization' && <span className="text-primary">{sortDirection === 'asc' ? '↑' : '↓'}</span>}
                </div>
              </th>
              <th
                className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider cursor-pointer hover:bg-accent transition-colors"
                onClick={() => handleSort('department')}
              >
                <div className="flex items-center gap-2">
                  Department
                  <ArrowUpDown className="h-4 w-4" />
                  {sortColumn === 'department' && <span className="text-primary">{sortDirection === 'asc' ? '↑' : '↓'}</span>}
                </div>
              </th>
              <th
                className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider cursor-pointer hover:bg-accent transition-colors"
                onClick={() => handleSort('arrivalMode')}
              >
                <div className="flex items-center gap-2">
                  Arrival Mode
                  <ArrowUpDown className="h-4 w-4" />
                  {sortColumn === 'arrivalMode' && <span className="text-primary">{sortDirection === 'asc' ? '↑' : '↓'}</span>}
                </div>
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                Actions
              </th>
            </tr>
          </thead>
          <tbody className="bg-card divide-y divide-border">
            {filteredVIPs.map((vip) => (
              <tr key={vip.id} className="hover:bg-accent transition-colors">
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">
                  {vip.name}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {vip.organization || '-'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {vip.department}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {vip.arrivalMode}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm">
                  <div className="flex gap-2">
                    <button
                      onClick={() => navigate(`/vips/${vip.id}/schedule`)}
                      className="inline-flex items-center px-3 py-1 text-blue-600 hover:text-blue-800 transition-colors"
                      style={{ minHeight: '36px' }}
                      title="View Schedule"
                    >
                      <Calendar className="h-4 w-4 mr-1" />
                      Schedule
                    </button>
                    <button
                      onClick={() => handleEdit(vip)}
                      className="inline-flex items-center px-3 py-1 text-primary hover:text-primary/80 transition-colors"
                      style={{ minHeight: '36px' }}
                    >
                      <Edit className="h-4 w-4 mr-1" />
                      Edit
                    </button>
                    <button
                      onClick={() => handleDelete(vip.id, vip.name)}
                      className="inline-flex items-center px-3 py-1 text-red-600 hover:text-red-800 transition-colors"
                      style={{ minHeight: '36px' }}
                    >
                      <Trash2 className="h-4 w-4 mr-1" />
                      Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Mobile/Tablet Card View - shows on small and medium screens */}
      <div className="lg:hidden space-y-4">
        {filteredVIPs.map((vip) => (
          <div key={vip.id} className="bg-card shadow-soft border border-border rounded-lg p-4">
            <div className="flex justify-between items-start mb-3">
              <div>
                <h3 className="text-lg font-semibold text-foreground">{vip.name}</h3>
                {vip.organization && (
                  <p className="text-sm text-muted-foreground mt-1">{vip.organization}</p>
                )}
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3 mb-4">
              <div>
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Department</p>
                <p className="text-sm text-foreground mt-1">{vip.department}</p>
              </div>
              <div>
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Arrival Mode</p>
                <p className="text-sm text-foreground mt-1">{vip.arrivalMode}</p>
              </div>
            </div>

            <div className="flex flex-col sm:flex-row gap-2 pt-3 border-t border-border">
              <button
                onClick={() => navigate(`/vips/${vip.id}/schedule`)}
                className="flex-1 inline-flex items-center justify-center px-4 py-2 border border-input text-sm font-medium rounded-md text-blue-600 bg-background hover:bg-blue-50 transition-colors"
                style={{ minHeight: '44px' }}
              >
                <Calendar className="h-5 w-5 mr-2" />
                Schedule
              </button>
              <button
                onClick={() => handleEdit(vip)}
                className="flex-1 inline-flex items-center justify-center px-4 py-2 border border-input text-sm font-medium rounded-md text-primary bg-background hover:bg-accent transition-colors"
                style={{ minHeight: '44px' }}
              >
                <Edit className="h-5 w-5 mr-2" />
                Edit
              </button>
              <button
                onClick={() => handleDelete(vip.id, vip.name)}
                className="flex-1 inline-flex items-center justify-center px-4 py-2 border border-input text-sm font-medium rounded-md text-red-600 bg-background hover:bg-red-50 transition-colors"
                style={{ minHeight: '44px' }}
              >
                <Trash2 className="h-5 w-5 mr-2" />
                Delete
              </button>
            </div>
          </div>
        ))}
      </div>

      {showForm && (
        <VIPForm
          vip={editingVIP}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
          isSubmitting={isSubmitting}
        />
      )}

      {/* Filter Modal */}
      <FilterModal
        isOpen={filterModalOpen}
        onClose={() => setFilterModalOpen(false)}
        filterGroups={[
          {
            label: 'Department',
            options: [
              { value: 'OFFICE_OF_DEVELOPMENT', label: 'Office of Development' },
              { value: 'ADMIN', label: 'Admin' },
            ],
            selectedValues: selectedDepartments,
            onToggle: handleDepartmentToggle,
          },
          {
            label: 'Arrival Mode',
            options: [
              { value: 'FLIGHT', label: 'Flight' },
              { value: 'SELF_DRIVING', label: 'Self Driving' },
            ],
            selectedValues: selectedArrivalModes,
            onToggle: handleArrivalModeToggle,
          },
        ]}
        onClear={handleClearFilters}
        onApply={() => {}}
      />
    </div>
  );
}
