import { useState, useMemo, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useLocation, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { ScheduleEvent, EventType } from '@/types';
import { formatDateTime } from '@/lib/utils';
import { Plus, Edit, Trash2, Search, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
import { EventForm, EventFormData } from '@/components/EventForm';
import { Loading } from '@/components/Loading';
import { InlineDriverSelector } from '@/components/InlineDriverSelector';

type ActivityFilter = 'ALL' | EventType;
type SortField = 'title' | 'type' | 'startTime' | 'status' | 'vips';
type SortDirection = 'asc' | 'desc';

export function EventList() {
  const queryClient = useQueryClient();
  const location = useLocation();
  const navigate = useNavigate();
  const [showForm, setShowForm] = useState(false);
  const [editingEvent, setEditingEvent] = useState<ScheduleEvent | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [activeFilter, setActiveFilter] = useState<ActivityFilter>('ALL');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortField, setSortField] = useState<SortField>('startTime');
  const [sortDirection, setSortDirection] = useState<SortDirection>('asc');

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

  // Handle opening a specific event from navigation state (e.g., from War Room)
  useEffect(() => {
    const state = location.state as { editEventId?: string } | null;
    if (state?.editEventId && events) {
      const eventToEdit = events.find(e => e.id === state.editEventId);
      if (eventToEdit) {
        setEditingEvent(eventToEdit);
        setShowForm(true);
        // Clear the state so refreshing doesn't re-open the form
        navigate(location.pathname, { replace: true, state: {} });
      }
    }
  }, [location.state, events, navigate, location.pathname]);

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

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

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

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

  const handleEdit = (event: ScheduleEvent) => {
    setEditingEvent(event);
    setShowForm(true);
  };

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

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

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

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      // Toggle direction if clicking the same field
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      // New field, default to ascending
      setSortField(field);
      setSortDirection('asc');
    }
  };

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

    let filtered = events;

    // Filter by type
    if (activeFilter !== 'ALL') {
      filtered = filtered.filter(event => event.type === activeFilter);
    }

    // Filter by search query
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(event => {
        // Search in title
        if (event.title?.toLowerCase().includes(query)) return true;

        // Search in description
        if (event.description?.toLowerCase().includes(query)) return true;

        // Search in location/pickup/dropoff
        if (event.location?.toLowerCase().includes(query)) return true;
        if (event.pickupLocation?.toLowerCase().includes(query)) return true;
        if (event.dropoffLocation?.toLowerCase().includes(query)) return true;

        // Search in VIP names
        if (event.vips?.some(vip => vip.name.toLowerCase().includes(query))) return true;

        // Search in driver name
        if (event.driver?.name.toLowerCase().includes(query)) return true;

        // Search in vehicle name
        if (event.vehicle?.name.toLowerCase().includes(query)) return true;

        return false;
      });
    }

    // Sort results
    const sorted = [...filtered].sort((a, b) => {
      let comparison = 0;

      switch (sortField) {
        case 'title':
          comparison = a.title.localeCompare(b.title);
          break;
        case 'type':
          comparison = a.type.localeCompare(b.type);
          break;
        case 'startTime':
          comparison = new Date(a.startTime).getTime() - new Date(b.startTime).getTime();
          break;
        case 'status':
          comparison = a.status.localeCompare(b.status);
          break;
        case 'vips':
          const aVipCount = a.vips?.length || 0;
          const bVipCount = b.vips?.length || 0;
          comparison = aVipCount - bVipCount;
          break;
      }

      return sortDirection === 'asc' ? comparison : -comparison;
    });

    return sorted;
  }, [events, activeFilter, searchQuery, sortField, sortDirection]);

  const filterTabs = useMemo(() => {
    if (!events) return [] as { label: string; value: ActivityFilter; count: number }[];
    return [
      { label: 'All', value: 'ALL' as ActivityFilter, count: events.length },
      { label: 'Transport', value: 'TRANSPORT' as ActivityFilter, count: events.filter(e => e.type === 'TRANSPORT').length },
      { label: 'Meals', value: 'MEAL' as ActivityFilter, count: events.filter(e => e.type === 'MEAL').length },
      { label: 'Events', value: 'EVENT' as ActivityFilter, count: events.filter(e => e.type === 'EVENT').length },
      { label: 'Meetings', value: 'MEETING' as ActivityFilter, count: events.filter(e => e.type === 'MEETING').length },
      { label: 'Accommodation', value: 'ACCOMMODATION' as ActivityFilter, count: events.filter(e => e.type === 'ACCOMMODATION').length },
    ];
  }, [events]);

  if (isLoading) {
    return <Loading message="Loading activities..." />;
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-foreground">Activities</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 Activity
        </button>
      </div>

      {/* Search Bar */}
      <div className="bg-card shadow-soft border border-border rounded-lg mb-4 p-4">
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <Search className="h-5 w-5 text-muted-foreground" />
          </div>
          <input
            type="text"
            placeholder="Search activities by title, location, VIP name, driver, or vehicle..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="block w-full pl-10 pr-3 py-2 border border-input rounded-md leading-5 bg-background placeholder-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary sm:text-sm transition-colors"
          />
          {searchQuery && (
            <button
              onClick={() => setSearchQuery('')}
              className="absolute inset-y-0 right-0 pr-3 flex items-center text-muted-foreground hover:text-foreground transition-colors"
            >
              <span className="text-sm font-medium">Clear</span>
            </button>
          )}
        </div>
        {searchQuery && (
          <p className="mt-2 text-sm text-muted-foreground">
            Found {filteredEvents.length} {filteredEvents.length === 1 ? 'activity' : 'activities'} matching "{searchQuery}"
          </p>
        )}
      </div>

      {/* Filter Tabs */}
      <div className="bg-card shadow-soft border border-border rounded-lg mb-4 p-4">
        <div className="flex flex-wrap gap-2">
          {filterTabs.map((tab) => (
            <button
              key={tab.value}
              onClick={() => setActiveFilter(tab.value)}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                activeFilter === tab.value
                  ? 'bg-primary text-white'
                  : 'bg-muted text-foreground hover:bg-accent'
              }`}
            >
              {tab.label} ({tab.count})
            </button>
          ))}
        </div>
      </div>

      {/* Activities Table */}
      {filteredEvents.length === 0 ? (
        <div className="bg-card shadow-soft border border-border rounded-lg p-12 text-center">
          <Search className="h-16 w-16 mx-auto mb-4 text-muted-foreground/50" />
          <h3 className="text-lg font-medium text-foreground mb-2">
            {searchQuery ? 'No activities found' : 'No activities yet'}
          </h3>
          <p className="text-muted-foreground">
            {searchQuery
              ? `No activities match "${searchQuery}". Try a different search term.`
              : 'Get started by adding your first activity.'}
          </p>
          {searchQuery && (
            <button
              onClick={() => setSearchQuery('')}
              className="mt-4 inline-flex items-center px-4 py-2 border border-border text-sm font-medium rounded-md text-foreground bg-card hover:bg-accent transition-colors"
            >
              Clear search
            </button>
          )}
        </div>
      ) : (
        <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('title')}
                >
                  <div className="flex items-center gap-1">
                    Title
                    {sortField === 'title' ? (
                      sortDirection === 'asc' ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
                    ) : (
                      <ArrowUpDown className="h-3 w-3 text-muted-foreground/50" />
                    )}
                  </div>
                </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('type')}
                >
                  <div className="flex items-center gap-1">
                    Type
                    {sortField === 'type' ? (
                      sortDirection === 'asc' ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
                    ) : (
                      <ArrowUpDown className="h-3 w-3 text-muted-foreground/50" />
                    )}
                  </div>
                </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('vips')}
                >
                  <div className="flex items-center gap-1">
                    VIPs
                    {sortField === 'vips' ? (
                      sortDirection === 'asc' ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
                    ) : (
                      <ArrowUpDown className="h-3 w-3 text-muted-foreground/50" />
                    )}
                  </div>
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                  Vehicle
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                  Driver
                </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('startTime')}
                >
                  <div className="flex items-center gap-1">
                    Start Time
                    {sortField === 'startTime' ? (
                      sortDirection === 'asc' ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
                    ) : (
                      <ArrowUpDown className="h-3 w-3 text-muted-foreground/50" />
                    )}
                  </div>
                </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-1">
                    Status
                    {sortField === 'status' ? (
                      sortDirection === 'asc' ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
                    ) : (
                      <ArrowUpDown className="h-3 w-3 text-muted-foreground/50" />
                    )}
                  </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">
              {filteredEvents?.map((event) => (
              <tr key={event.id} className="hover:bg-muted/50 transition-colors">
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">
                  {event.title}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`px-2 py-1 text-xs rounded-full ${
                    event.type === 'TRANSPORT' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300' :
                    event.type === 'MEAL' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
                    event.type === 'EVENT' ? 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300' :
                    event.type === 'MEETING' ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300' :
                    'bg-muted text-muted-foreground'
                  }`}>
                    {event.type}
                  </span>
                </td>
                <td className="px-6 py-4 text-sm text-muted-foreground">
                  {event.vips && event.vips.length > 0
                    ? event.vips.map(vip => vip.name).join(', ')
                    : 'No VIPs assigned'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {event.vehicle ? (
                    <div>
                      <div className="text-foreground">{event.vehicle.name}</div>
                      <div className="text-xs text-muted-foreground">
                        {event.vips?.length || 0}/{event.vehicle.seatCapacity} seats
                      </div>
                    </div>
                  ) : (
                    <span className="text-muted-foreground">No vehicle</span>
                  )}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  <InlineDriverSelector
                    eventId={event.id}
                    currentDriverId={event.driverId}
                    currentDriverName={event.driver?.name}
                  />
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {formatDateTime(event.startTime)}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`px-2 py-1 text-xs rounded-full ${
                    event.status === 'SCHEDULED' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300' :
                    event.status === 'IN_PROGRESS' ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300' :
                    event.status === 'COMPLETED' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
                    'bg-muted text-muted-foreground'
                  }`}>
                    {event.status}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm">
                  <div className="flex gap-2">
                    <button
                      onClick={() => handleEdit(event)}
                      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(event.id, event.title)}
                      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>
      )}

      {showForm && (
        <EventForm
          event={editingEvent}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
          isSubmitting={isSubmitting}
        />
      )}
    </div>
  );
}
