import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { apiCall } from '../config/api';

interface ScheduleEvent {
  id: string;
  title: string;
  location: string;
  startTime: string;
  endTime: string;
  status: 'scheduled' | 'in-progress' | 'completed' | 'cancelled';
  type: 'transport' | 'meeting' | 'event' | 'meal' | 'accommodation';
}

interface Vip {
  id: string;
  name: string;
  organization: string;
  transportMode: 'flight' | 'self-driving';
  flightNumber?: string;
  flights?: Array<{
    flightNumber: string;
    flightDate: string;
    segment: number;
  }>;
  expectedArrival?: string;
  arrivalTime?: string;
  needsAirportPickup?: boolean;
  needsVenueTransport: boolean;
  notes?: string;
  currentEvent?: ScheduleEvent;
  nextEvent?: ScheduleEvent;
  nextEventTime?: string;
}

interface Driver {
  id: string;
  name: string;
  phone: string;
  currentLocation: { lat: number; lng: number };
  assignedVipIds: string[];
}

const Dashboard: React.FC = () => {
  const [vips, setVips] = useState<Vip[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [loading, setLoading] = useState(true);

  // Helper functions for event management
  const getCurrentEvent = (events: ScheduleEvent[]) => {
    const now = new Date();
    return events.find(event => 
      new Date(event.startTime) <= now && 
      new Date(event.endTime) > now && 
      event.status === 'in-progress'
    ) || null;
  };

  const getNextEvent = (events: ScheduleEvent[]) => {
    const now = new Date();
    const upcomingEvents = events.filter(event => 
      new Date(event.startTime) > now && event.status === 'scheduled'
    ).sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime());
    
    return upcomingEvents.length > 0 ? upcomingEvents[0] : null;
  };

  const formatTime = (timeString: string) => {
    return new Date(timeString).toLocaleString([], {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const token = localStorage.getItem('authToken');
        const authHeaders = {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        };
        
        const [vipsResponse, driversResponse] = await Promise.all([
          apiCall('/api/vips', { headers: authHeaders }),
          apiCall('/api/drivers', { headers: authHeaders })
        ]);
        
        if (!vipsResponse.ok || !driversResponse.ok) {
          throw new Error('Failed to fetch data');
        }
        
        const vipsData = await vipsResponse.json();
        const driversData = await driversResponse.json();
        
        // Fetch schedule for each VIP and determine current/next events
        const vipsWithSchedules = await Promise.all(
          vipsData.map(async (vip: Vip) => {
            try {
              const scheduleResponse = await apiCall(`/api/vips/${vip.id}/schedule`, {
                headers: authHeaders
              });
              
              if (scheduleResponse.ok) {
                const scheduleData = await scheduleResponse.json();
                
                const currentEvent = getCurrentEvent(scheduleData);
                const nextEvent = getNextEvent(scheduleData);
                
                return {
                  ...vip,
                  currentEvent,
                  nextEvent,
                  nextEventTime: nextEvent ? nextEvent.startTime : null
                };
              } else {
                return { ...vip, currentEvent: null, nextEvent: null, nextEventTime: null };
              }
            } catch (error) {
              console.error(`Error fetching schedule for VIP ${vip.id}:`, error);
              return { ...vip, currentEvent: null, nextEvent: null, nextEventTime: null };
            }
          })
        );
        
        // Sort VIPs by next event time (soonest first), then by name
        const sortedVips = vipsWithSchedules.sort((a, b) => {
          // VIPs with current events first
          if (a.currentEvent && !b.currentEvent) return -1;
          if (!a.currentEvent && b.currentEvent) return 1;
          
          // Then by next event time (soonest first)
          if (a.nextEventTime && b.nextEventTime) {
            return new Date(a.nextEventTime).getTime() - new Date(b.nextEventTime).getTime();
          }
          if (a.nextEventTime && !b.nextEventTime) return -1;
          if (!a.nextEventTime && b.nextEventTime) return 1;
          
          // Finally by name if no events
          return a.name.localeCompare(b.name);
        });
        
        setVips(sortedVips);
        setDrivers(driversData);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-64">
        <div className="bg-white rounded-2xl shadow-lg p-8 flex items-center space-x-4">
          <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
          <span className="text-lg font-medium text-slate-700">Loading dashboard...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
              VIP Coordinator Dashboard
            </h1>
            <p className="text-slate-600 mt-2">Real-time overview of VIP activities and coordination</p>
          </div>
          <div className="flex items-center space-x-4">
            <div className="bg-gradient-to-r from-blue-500 to-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium">
              {vips.length} Active VIPs
            </div>
            <div className="bg-gradient-to-r from-green-500 to-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium">
              {drivers.length} Drivers
            </div>
          </div>
        </div>
      </div>
      
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
        {/* VIP Status Dashboard */}
        <div className="xl:col-span-2">
          <div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
            <div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-6 py-4 border-b border-slate-200/60">
              <h2 className="text-xl font-bold text-slate-800 flex items-center">
                VIP Status Dashboard
                <span className="ml-2 bg-blue-100 text-blue-800 text-sm font-medium px-2.5 py-0.5 rounded-full">
                  {vips.length} VIPs
                </span>
              </h2>
            </div>
            <div className="p-6">
              {vips.length === 0 ? (
                <div className="text-center py-12">
                  <div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <div className="w-8 h-8 bg-slate-300 rounded-full"></div>
                  </div>
                  <p className="text-slate-500 font-medium">No VIPs currently scheduled</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {vips.map((vip) => {
                    const hasCurrentEvent = !!vip.currentEvent;
                    const hasNextEvent = !!vip.nextEvent;
                    
                    return (
                      <div key={vip.id} className={`
                        relative rounded-xl border-2 p-6 transition-all duration-200 hover:shadow-lg
                        ${hasCurrentEvent 
                          ? 'border-amber-300 bg-gradient-to-r from-amber-50 to-orange-50' 
                          : hasNextEvent 
                          ? 'border-blue-300 bg-gradient-to-r from-blue-50 to-indigo-50' 
                          : 'border-slate-200 bg-slate-50'
                        }
                      `}>
                        <div className="flex justify-between items-start">
                          <div className="flex-1">
                            <div className="flex items-center gap-3 mb-3">
                              <h3 className="text-lg font-bold text-slate-900">{vip.name}</h3>
                              {hasCurrentEvent && (
                                <span className="bg-gradient-to-r from-amber-500 to-orange-500 text-white px-3 py-1 rounded-full text-xs font-bold animate-pulse">
                                  ACTIVE
                                </span>
                              )}
                            </div>
                            <p className="text-slate-600 text-sm mb-4">{vip.organization}</p>
                            
                            {/* Current Event */}
                            {vip.currentEvent && (
                              <div className="bg-white border border-amber-200 rounded-lg p-4 mb-3 shadow-sm">
                                <div className="flex items-center gap-2 mb-2">
                                  <span className="text-amber-600 font-bold text-sm">CURRENT EVENT</span>
                                </div>
                                <div className="flex items-center gap-2 mb-1">
                                  <span className="font-semibold text-slate-900">{vip.currentEvent.title}</span>
                                </div>
                                <p className="text-slate-600 text-sm mb-1">Location: {vip.currentEvent.location}</p>
                                <p className="text-slate-500 text-xs">Until {formatTime(vip.currentEvent.endTime)}</p>
                              </div>
                            )}
                            
                            {/* Next Event */}
                            {vip.nextEvent && (
                              <div className="bg-white border border-blue-200 rounded-lg p-4 mb-3 shadow-sm">
                                <div className="flex items-center gap-2 mb-2">
                                  <span className="text-blue-600 font-bold text-sm">NEXT EVENT</span>
                                </div>
                                <div className="flex items-center gap-2 mb-1">
                                  <span className="font-semibold text-slate-900">{vip.nextEvent.title}</span>
                                </div>
                                <p className="text-slate-600 text-sm mb-1">Location: {vip.nextEvent.location}</p>
                                <p className="text-slate-500 text-xs">{formatTime(vip.nextEvent.startTime)} - {formatTime(vip.nextEvent.endTime)}</p>
                              </div>
                            )}
                            
                            {/* No Events */}
                            {!vip.currentEvent && !vip.nextEvent && (
                              <div className="bg-white border border-slate-200 rounded-lg p-4 mb-3">
                                <p className="text-slate-500 text-sm italic">No scheduled events</p>
                              </div>
                            )}
                            
                            {/* Transport Info */}
                            <div className="flex items-center gap-2 text-xs text-slate-500 bg-white/50 rounded-lg px-3 py-2">
                              {vip.transportMode === 'flight' ? (
                                <span>Flight: {vip.flights && vip.flights.length > 0 ? 
                                  vip.flights.map(f => f.flightNumber).join(' → ') : 
                                  vip.flightNumber || 'TBD'}
                                </span>
                              ) : (
                                <span>Self-driving | Expected: {vip.expectedArrival ? formatTime(vip.expectedArrival) : 'TBD'}</span>
                              )}
                            </div>
                          </div>
                          
                          <div className="flex flex-col gap-2 ml-6">
                            <Link 
                              to={`/vips/${vip.id}`} 
                              className="bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 text-center shadow-lg hover:shadow-xl"
                            >
                              Details
                            </Link>
                            <Link 
                              to={`/vips/${vip.id}#schedule`} 
                              className="bg-gradient-to-r from-slate-500 to-slate-600 hover:from-slate-600 hover:to-slate-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 text-center shadow-lg hover:shadow-xl"
                            >
                              Schedule
                            </Link>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Drivers Card */}
          <div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
            <div className="bg-gradient-to-r from-green-50 to-emerald-50 px-6 py-4 border-b border-slate-200/60">
              <h2 className="text-lg font-bold text-slate-800 flex items-center">
                Available Drivers
                <span className="ml-2 bg-green-100 text-green-800 text-sm font-medium px-2.5 py-0.5 rounded-full">
                  {drivers.length}
                </span>
              </h2>
            </div>
            <div className="p-6">
              {drivers.length === 0 ? (
                <div className="text-center py-8">
                  <div className="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-3">
                    <div className="w-6 h-6 bg-slate-300 rounded-full"></div>
                  </div>
                  <p className="text-slate-500 text-sm">No drivers available</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {drivers.map((driver) => (
                    <div key={driver.id} className="bg-slate-50 rounded-lg p-4 border border-slate-200">
                      <div className="flex items-center justify-between">
                        <div>
                          <h4 className="font-semibold text-slate-900">{driver.name}</h4>
                          <p className="text-slate-600 text-sm">{driver.phone}</p>
                        </div>
                        <div className="text-right">
                          <span className="bg-blue-100 text-blue-800 text-xs font-medium px-2 py-1 rounded-full">
                            {driver.assignedVipIds.length} VIPs
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Quick Actions Card */}
          <div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
            <div className="bg-gradient-to-r from-purple-50 to-pink-50 px-6 py-4 border-b border-slate-200/60">
              <h2 className="text-lg font-bold text-slate-800">Quick Actions</h2>
            </div>
            <div className="p-6 space-y-3">
              <Link 
                to="/vips" 
                className="block w-full bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white px-4 py-3 rounded-lg font-medium transition-all duration-200 text-center shadow-lg hover:shadow-xl"
              >
                Manage VIPs
              </Link>
              <Link 
                to="/drivers" 
                className="block w-full bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-4 py-3 rounded-lg font-medium transition-all duration-200 text-center shadow-lg hover:shadow-xl"
              >
                Manage Drivers
              </Link>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
