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 { Driver } from '@/types';
import { Plus, Edit, Trash2, Search, X, Filter, ArrowUpDown, Send, Eye } from 'lucide-react';
import { DriverForm, DriverFormData } from '@/components/DriverForm';
import { TableSkeleton, CardSkeleton } from '@/components/Skeleton';
import { FilterModal } from '@/components/FilterModal';
import { FilterChip } from '@/components/FilterChip';
import { useDebounce } from '@/hooks/useDebounce';
import { DriverChatBubble } from '@/components/DriverChatBubble';
import { DriverChatModal } from '@/components/DriverChatModal';
import { DriverScheduleModal } from '@/components/DriverScheduleModal';
import { useUnreadCounts } from '@/hooks/useSignalMessages';

export function DriverList() {
  const queryClient = useQueryClient();
  const [showForm, setShowForm] = useState(false);
  const [editingDriver, setEditingDriver] = useState<Driver | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

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

  // Chat state
  const [chatDriver, setChatDriver] = useState<Driver | null>(null);

  // Schedule modal state
  const [scheduleDriver, setScheduleDriver] = useState<Driver | null>(null);

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

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

  // Fetch unread message counts
  const { data: unreadCounts } = useUnreadCounts();

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

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

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

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

  const sendScheduleMutation = useMutation({
    mutationFn: async ({ id, date }: { id: string; date?: string }) => {
      const { data } = await api.post(`/drivers/${id}/send-schedule`, { date, format: 'both' });
      return data;
    },
    onSuccess: (data) => {
      toast.success(data.message || 'Schedule sent successfully');
    },
    onError: (error: any) => {
      console.error('[DRIVER] Failed to send schedule:', error);
      toast.error(error.response?.data?.message || 'Failed to send schedule');
    },
  });

  const handleSendSchedule = (driver: Driver) => {
    if (!driver.phone) {
      toast.error('Driver does not have a phone number');
      return;
    }
    sendScheduleMutation.mutate({ id: driver.id });
  };

  // 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 drivers
  const filteredDrivers = useMemo(() => {
    if (!drivers) return [];

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

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

      return matchesSearch && matchesDepartment;
    });

    // 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;
  }, [drivers, debouncedSearchTerm, selectedDepartments, sortColumn, sortDirection]);

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

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

  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 getFilterLabel = (value: string) => {
    const labels = {
      'OFFICE_OF_DEVELOPMENT': 'Office of Development',
      'ADMIN': 'Admin',
    };
    return labels[value as keyof typeof labels] || value;
  };

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

  const handleEdit = (driver: Driver) => {
    setEditingDriver(driver);
    setShowForm(true);
  };

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

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

  const handleCancel = () => {
    setShowForm(false);
    setEditingDriver(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">Drivers</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 Driver
          </button>
        </div>
        <div className="hidden lg:block">
          <TableSkeleton rows={8} />
        </div>
        <div className="lg:hidden">
          <CardSkeleton 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">Drivers</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 Driver
        </button>
      </div>

      {/* Search and Filter Section */}
      <div className="bg-card border border-border shadow-soft 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 or phone..."
              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 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-card hover:bg-accent hover:text-accent-foreground font-medium transition-colors"
            style={{ minHeight: '44px' }}
          >
            <Filter className="h-5 w-5 mr-2" />
            Filters
            {selectedDepartments.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}
              </span>
            )}
          </button>
        </div>

        {/* Active Filter Chips */}
        {selectedDepartments.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)}
                onRemove={() => handleRemoveDepartmentFilter(dept)}
              />
            ))}
          </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">{filteredDrivers.length}</span> of <span className="font-medium text-foreground">{drivers?.length || 0}</span> drivers
            {debouncedSearchTerm !== searchTerm && <span className="ml-2 text-muted-foreground/60">(searching...)</span>}
          </div>
          {(searchTerm || selectedDepartments.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 border border-border shadow-medium 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 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 cursor-pointer hover:bg-accent transition-colors"
                onClick={() => handleSort('phone')}
              >
                <div className="flex items-center gap-2">
                  Phone
                  <ArrowUpDown className="h-4 w-4" />
                  {sortColumn === 'phone' && <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 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">
                Assigned Events
              </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">
            {filteredDrivers.map((driver) => (
              <tr key={driver.id} className="hover:bg-accent transition-colors">
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">
                  <div className="flex items-center gap-2">
                    {driver.name}
                    <DriverChatBubble
                      unreadCount={unreadCounts?.[driver.id] || 0}
                      onClick={() => setChatDriver(driver)}
                    />
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {driver.phone}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {driver.department || '-'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {driver.events?.length || 0}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm">
                  <div className="flex gap-2">
                    <button
                      onClick={() => setScheduleDriver(driver)}
                      className="inline-flex items-center px-3 py-1 text-blue-600 hover:text-blue-800 transition-colors"
                      style={{ minHeight: '36px' }}
                      title="View driver's schedule"
                    >
                      <Eye className="h-4 w-4 mr-1" />
                      View
                    </button>
                    <button
                      onClick={() => handleSendSchedule(driver)}
                      disabled={sendScheduleMutation.isPending}
                      className="inline-flex items-center px-3 py-1 text-green-600 hover:text-green-800 transition-colors disabled:opacity-50"
                      style={{ minHeight: '36px' }}
                      title="Send today's schedule via Signal"
                    >
                      <Send className="h-4 w-4 mr-1" />
                      Send
                    </button>
                    <button
                      onClick={() => handleEdit(driver)}
                      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(driver.id, driver.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">
        {filteredDrivers.map((driver) => (
          <div key={driver.id} className="bg-card border border-border shadow-soft rounded-lg p-4">
            <div className="mb-3 flex items-start justify-between">
              <div>
                <h3 className="text-lg font-semibold text-foreground">{driver.name}</h3>
                <p className="text-sm text-muted-foreground mt-1">{driver.phone}</p>
              </div>
              <DriverChatBubble
                unreadCount={unreadCounts?.[driver.id] || 0}
                onClick={() => setChatDriver(driver)}
              />
            </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">{driver.department || '-'}</p>
              </div>
              <div>
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Assigned Events</p>
                <p className="text-sm text-foreground mt-1">{driver.events?.length || 0}</p>
              </div>
            </div>

            <div className="flex flex-col sm:flex-row gap-2 pt-3 border-t border-border">
              <button
                onClick={() => setScheduleDriver(driver)}
                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-card hover:bg-blue-50 dark:hover:bg-blue-950/20 transition-colors"
                style={{ minHeight: '44px' }}
              >
                <Eye className="h-5 w-5 mr-2" />
                View Schedule
              </button>
              <button
                onClick={() => handleSendSchedule(driver)}
                disabled={sendScheduleMutation.isPending}
                className="flex-1 inline-flex items-center justify-center px-4 py-2 border border-input text-sm font-medium rounded-md text-green-600 bg-card hover:bg-green-50 dark:hover:bg-green-950/20 transition-colors disabled:opacity-50"
                style={{ minHeight: '44px' }}
              >
                <Send className="h-5 w-5 mr-2" />
                Send
              </button>
              <button
                onClick={() => handleEdit(driver)}
                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-card hover:bg-accent hover:text-accent-foreground transition-colors"
                style={{ minHeight: '44px' }}
              >
                <Edit className="h-5 w-5 mr-2" />
                Edit
              </button>
              <button
                onClick={() => handleDelete(driver.id, driver.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-card hover:bg-red-50 dark:hover:bg-red-950/20 transition-colors"
                style={{ minHeight: '44px' }}
              >
                <Trash2 className="h-5 w-5 mr-2" />
                Delete
              </button>
            </div>
          </div>
        ))}
      </div>

      {showForm && (
        <DriverForm
          driver={editingDriver}
          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,
          },
        ]}
        onClear={handleClearFilters}
        onApply={() => {}}
      />

      {/* Driver Chat Modal */}
      <DriverChatModal
        driver={chatDriver}
        isOpen={!!chatDriver}
        onClose={() => setChatDriver(null)}
      />

      {/* Driver Schedule Modal */}
      <DriverScheduleModal
        driver={scheduleDriver}
        isOpen={!!scheduleDriver}
        onClose={() => setScheduleDriver(null)}
      />
    </div>
  );
}
