import { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { Plus, Edit, Trash2, Plane, Search, X, Filter, ArrowUpDown } from 'lucide-react';
import { FlightForm, FlightFormData } from '@/components/FlightForm';
import { TableSkeleton } from '@/components/Skeleton';
import { ErrorMessage } from '@/components/ErrorMessage';
import { FilterModal } from '@/components/FilterModal';
import { FilterChip } from '@/components/FilterChip';
import { useDebounce } from '@/hooks/useDebounce';

interface Flight {
  id: string;
  vipId: string;
  vip?: {
    name: string;
    organization: string | null;
  };
  flightNumber: string;
  flightDate: string;
  segment: number;
  departureAirport: string;
  arrivalAirport: string;
  scheduledDeparture: string | null;
  scheduledArrival: string | null;
  actualDeparture: string | null;
  actualArrival: string | null;
  status: string | null;
}

export function FlightList() {
  const queryClient = useQueryClient();
  const [showForm, setShowForm] = useState(false);
  const [editingFlight, setEditingFlight] = useState<Flight | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Search and filter state
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedStatuses, setSelectedStatuses] = useState<string[]>([]);
  const [filterModalOpen, setFilterModalOpen] = useState(false);

  // Sort state
  const [sortColumn, setSortColumn] = useState<'flightNumber' | 'departureAirport' | 'arrivalAirport' | 'status'>('flightNumber');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');

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

  const { data: flights, isLoading, isError, error, refetch } = useQuery<Flight[]>({
    queryKey: ['flights'],
    queryFn: async () => {
      const { data } = await api.get('/flights');
      return data;
    },
  });

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

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

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

  // Filter and sort flights
  const filteredFlights = useMemo(() => {
    if (!flights) return [];

    // First filter
    let filtered = flights.filter((flight) => {
      // Search by flight number, VIP name, or route (using debounced term)
      const matchesSearch = debouncedSearchTerm === '' ||
        flight.flightNumber.toLowerCase().includes(debouncedSearchTerm.toLowerCase()) ||
        flight.vip?.name.toLowerCase().includes(debouncedSearchTerm.toLowerCase()) ||
        flight.departureAirport.toLowerCase().includes(debouncedSearchTerm.toLowerCase()) ||
        flight.arrivalAirport.toLowerCase().includes(debouncedSearchTerm.toLowerCase());

      // Filter by status
      const matchesStatus = selectedStatuses.length === 0 ||
        (flight.status && selectedStatuses.includes(flight.status.toLowerCase()));

      return matchesSearch && matchesStatus;
    });

    // Then sort
    filtered.sort((a, b) => {
      let aValue = a[sortColumn] || '';
      let bValue = b[sortColumn] || '';

      if (typeof aValue === 'string') aValue = aValue.toLowerCase();
      if (typeof bValue === 'string') bValue = bValue.toLowerCase();

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

    return filtered;
  }, [flights, debouncedSearchTerm, selectedStatuses, sortColumn, sortDirection]);

  const handleStatusToggle = (status: string) => {
    setSelectedStatuses((prev) =>
      prev.includes(status)
        ? prev.filter((s) => s !== status)
        : [...prev, status]
    );
  };

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

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

  const handleRemoveStatusFilter = (status: string) => {
    setSelectedStatuses((prev) => prev.filter((s) => s !== status));
  };

  const getFilterLabel = (value: string) => {
    const labels: Record<string, string> = {
      'scheduled': 'Scheduled',
      'boarding': 'Boarding',
      'departed': 'Departed',
      'en-route': 'En Route',
      'landed': 'Landed',
      'delayed': 'Delayed',
      'cancelled': 'Cancelled',
    };
    return labels[value] || value;
  };

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

  const handleEdit = (flight: Flight) => {
    setEditingFlight(flight);
    setShowForm(true);
  };

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

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

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

  const formatTime = (isoString: string | null) => {
    if (!isoString) return '-';
    return new Date(isoString).toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getStatusColor = (status: string | null) => {
    switch (status?.toLowerCase()) {
      case 'scheduled':
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
      case 'boarding':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
      case 'departed':
      case 'en-route':
        return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
      case 'landed':
        return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
      case 'delayed':
        return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
      case 'cancelled':
        return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
      default:
        return 'bg-muted text-muted-foreground';
    }
  };

  if (isLoading) {
    return (
      <div>
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-3xl font-bold text-foreground">Flights</h1>
          <button
            disabled
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary/50 cursor-not-allowed"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Flight
          </button>
        </div>
        <TableSkeleton rows={8} />
      </div>
    );
  }

  if (isError) {
    return (
      <ErrorMessage
        title="Failed to load flights"
        message={(error as any)?.message || 'An error occurred while loading flights'}
        onRetry={() => refetch()}
      />
    );
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-foreground">Flights</h1>
        <button
          onClick={handleAdd}
          className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90 transition-colors"
        >
          <Plus className="h-4 w-4 mr-2" />
          Add Flight
        </button>
      </div>

      {/* Search and Filter Section */}
      {flights && flights.length > 0 && (
        <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 flight number, VIP, or route..."
                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-primary focus:border-primary text-base bg-background transition-colors"
                style={{ minHeight: '44px' }}
              />
            </div>

            {/* Filter Button */}
            <button
              onClick={() => setFilterModalOpen(true)}
              className="inline-flex items-center px-4 py-2 border border-border rounded-md text-foreground bg-card hover:bg-accent font-medium transition-colors"
              style={{ minHeight: '44px' }}
            >
              <Filter className="h-5 w-5 mr-2" />
              Filters
              {selectedStatuses.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">
                  {selectedStatuses.length}
                </span>
              )}
            </button>
          </div>

          {/* Active Filter Chips */}
          {selectedStatuses.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>
              {selectedStatuses.map((status) => (
                <FilterChip
                  key={status}
                  label={getFilterLabel(status)}
                  onRemove={() => handleRemoveStatusFilter(status)}
                />
              ))}
            </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">{filteredFlights.length}</span> of <span className="font-medium text-foreground">{flights.length}</span> flights
              {debouncedSearchTerm !== searchTerm && <span className="ml-2 text-muted-foreground/70">(searching...)</span>}
            </div>
            {(searchTerm || selectedStatuses.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>
      )}

      {flights && flights.length > 0 ? (
        <div className="bg-card shadow-medium 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 cursor-pointer hover:bg-accent select-none transition-colors"
                  onClick={() => handleSort('flightNumber')}
                >
                  <div className="flex items-center gap-2">
                    Flight
                    <ArrowUpDown className="h-4 w-4" />
                    {sortColumn === 'flightNumber' && <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">
                  VIP
                </th>
                <th
                  className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase cursor-pointer hover:bg-accent select-none transition-colors"
                  onClick={() => handleSort('departureAirport')}
                >
                  <div className="flex items-center gap-2">
                    Route
                    <ArrowUpDown className="h-4 w-4" />
                    {sortColumn === 'departureAirport' && <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">
                  Scheduled
                </th>
                <th
                  className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase cursor-pointer hover:bg-accent select-none transition-colors"
                  onClick={() => handleSort('status')}
                >
                  <div className="flex items-center gap-2">
                    Status
                    <ArrowUpDown className="h-4 w-4" />
                    {sortColumn === 'status' && <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">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-card divide-y divide-border">
              {filteredFlights.map((flight) => (
                <tr key={flight.id} className="hover:bg-muted/50 transition-colors">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center">
                      <Plane className="h-4 w-4 text-muted-foreground mr-2" />
                      <div>
                        <div className="text-sm font-medium text-foreground">
                          {flight.flightNumber}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          Segment {flight.segment}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm">
                    <div className="font-medium text-foreground">{flight.vip?.name}</div>
                    {flight.vip?.organization && (
                      <div className="text-xs text-muted-foreground">{flight.vip.organization}</div>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                    <div className="flex items-center">
                      <span className="font-medium text-foreground">{flight.departureAirport}</span>
                      <span className="mx-2">→</span>
                      <span className="font-medium text-foreground">{flight.arrivalAirport}</span>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                    <div className="text-xs">
                      <div>Dep: {formatTime(flight.scheduledDeparture)}</div>
                      <div>Arr: {formatTime(flight.scheduledArrival)}</div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span
                      className={`px-2 py-1 text-xs rounded-full ${getStatusColor(
                        flight.status
                      )}`}
                    >
                      {flight.status || 'Unknown'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm">
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleEdit(flight)}
                        className="inline-flex items-center px-3 py-1 text-primary hover:text-primary/80 transition-colors"
                      >
                        <Edit className="h-4 w-4 mr-1" />
                        Edit
                      </button>
                      <button
                        onClick={() => handleDelete(flight.id, flight.flightNumber)}
                        className="inline-flex items-center px-3 py-1 text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                      >
                        <Trash2 className="h-4 w-4 mr-1" />
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="bg-card shadow-soft border border-border rounded-lg p-12 text-center">
          <Plane className="h-12 w-12 text-muted-foreground/50 mx-auto mb-4" />
          <p className="text-muted-foreground mb-4">No flights tracked yet.</p>
          <button
            onClick={handleAdd}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90 transition-colors"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Your First Flight
          </button>
        </div>
      )}

      {showForm && (
        <FlightForm
          flight={editingFlight}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
          isSubmitting={isSubmitting}
        />
      )}

      {/* Filter Modal */}
      <FilterModal
        isOpen={filterModalOpen}
        onClose={() => setFilterModalOpen(false)}
        filterGroups={[
          {
            label: 'Flight Status',
            options: [
              { value: 'scheduled', label: 'Scheduled' },
              { value: 'boarding', label: 'Boarding' },
              { value: 'departed', label: 'Departed' },
              { value: 'en-route', label: 'En Route' },
              { value: 'landed', label: 'Landed' },
              { value: 'delayed', label: 'Delayed' },
              { value: 'cancelled', label: 'Cancelled' },
            ],
            selectedValues: selectedStatuses,
            onToggle: handleStatusToggle,
          },
        ]}
        onClear={handleClearFilters}
        onApply={() => {}}
      />
    </div>
  );
}
