import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Users, Car, Plane, Clock, AlertTriangle, Link2 } from 'lucide-react';
import { VIP, Driver, ScheduleEvent, Flight } from '@/types';
import { useFormattedDate } from '@/hooks/useFormattedDate';
import { FlightProgressBar } from '@/components/FlightProgressBar';
import { groupFlightsIntoJourneys, formatLayoverDuration } from '@/lib/journeyUtils';

export function Dashboard() {
  const { formatDate, formatDateTime, formatTime } = useFormattedDate();
  const { data: vips } = useQuery<VIP[]>({
    queryKey: ['vips'],
    queryFn: async () => {
      const { data } = await api.get('/vips');
      return data;
    },
  });

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

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

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

  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  const eventsToday = events?.filter((e) => {
    const eventDate = new Date(e.startTime);
    return eventDate >= today && eventDate < tomorrow && e.status !== 'CANCELLED';
  }).length || 0;

  const flightsToday = flights?.filter((f) => {
    const flightDate = new Date(f.flightDate);
    return flightDate >= today && flightDate < tomorrow;
  }).length || 0;

  const upcomingEvents = events
    ?.filter((e) => e.status === 'SCHEDULED' && new Date(e.startTime) >= today)
    .sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime())
    .slice(0, 5) || [];

  const upcomingFlights = flights
    ?.filter((f) => {
      const flightDate = new Date(f.flightDate);
      return flightDate >= today && f.status !== 'cancelled';
    })
    .sort((a, b) => new Date(a.flightDate).getTime() - new Date(b.flightDate).getTime())
    .slice(0, 5) || [];

  const journeys = useMemo(() => {
    if (!flights || flights.length === 0) return [];
    return groupFlightsIntoJourneys(flights);
  }, [flights]);

  const upcomingJourneys = useMemo(() => {
    return journeys
      .filter(j => j.effectiveStatus !== 'cancelled' && j.effectiveStatus !== 'landed')
      .sort((a, b) => {
        // Active journeys first, then by ETA
        if (a.effectiveStatus === 'active' && b.effectiveStatus !== 'active') return -1;
        if (b.effectiveStatus === 'active' && a.effectiveStatus !== 'active') return 1;
        const etaA = a.flights[a.currentSegmentIndex]?.estimatedArrival || a.flights[a.currentSegmentIndex]?.scheduledArrival || '';
        const etaB = b.flights[b.currentSegmentIndex]?.estimatedArrival || b.flights[b.currentSegmentIndex]?.scheduledArrival || '';
        return etaA.localeCompare(etaB);
      })
      .slice(0, 5);
  }, [journeys]);

  const stats = [
    {
      name: 'Total VIPs',
      value: vips?.length || 0,
      icon: Users,
      color: 'bg-blue-500',
    },
    {
      name: 'Active Drivers',
      value: drivers?.length || 0,
      icon: Car,
      color: 'bg-green-500',
    },
    {
      name: 'Events Today',
      value: eventsToday,
      icon: Clock,
      color: 'bg-purple-500',
    },
    {
      name: 'Flights Today',
      value: flightsToday,
      icon: Plane,
      color: 'bg-indigo-500',
    },
  ];

  return (
    <div>
      <h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-6 md:mb-8">Dashboard</h1>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 mb-6 md:mb-8">
        {stats.map((stat) => {
          const Icon = stat.icon;
          return (
            <div
              key={stat.name}
              className="bg-card overflow-hidden shadow-soft rounded-lg border border-border transition-colors"
            >
              <div className="p-5">
                <div className="flex items-center">
                  <div className={`flex-shrink-0 ${stat.color} rounded-md p-3`}>
                    <Icon className="h-6 w-6 text-white" />
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-muted-foreground truncate">
                        {stat.name}
                      </dt>
                      <dd className="text-3xl font-semibold text-foreground">
                        {stat.value}
                      </dd>
                    </dl>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Recent VIPs */}
      <div className="bg-card shadow-medium rounded-lg p-6 mb-8 border border-border">
        <h2 className="text-lg font-medium text-foreground mb-4">Recent VIPs</h2>
        {vips && vips.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-border">
              <thead>
                <tr>
                  <th className="px-6 py-3 bg-muted/30 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Name
                  </th>
                  <th className="px-6 py-3 bg-muted/30 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Organization
                  </th>
                  <th className="px-6 py-3 bg-muted/30 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Arrival Mode
                  </th>
                  <th className="px-6 py-3 bg-muted/30 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Events
                  </th>
                </tr>
              </thead>
              <tbody className="bg-card divide-y divide-border">
                {vips.slice(0, 5).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.arrivalMode}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                      {vip.events?.length || 0}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-sm text-muted-foreground text-center py-4">
            No VIPs yet. Add your first VIP to get started.
          </p>
        )}
      </div>

      {/* Flight Status Overview */}
      <div className="bg-card shadow-medium rounded-lg p-6 mb-8 border border-border">
        <h2 className="text-lg font-medium text-foreground mb-4 flex items-center gap-2">
          <Plane className="h-5 w-5" />
          Flight Status
        </h2>

        {/* Journey status summary */}
        {journeys.length > 0 && (
          <div className="flex flex-wrap gap-4 mb-4 pb-4 border-b border-border">
            {(() => {
              const inFlight = journeys.filter(j => j.effectiveStatus === 'active').length;
              const connectionRisk = journeys.filter(j => j.hasLayoverRisk).length;
              const cancelled = journeys.filter(j => j.effectiveStatus === 'cancelled').length;
              const landed = journeys.filter(j => j.effectiveStatus === 'landed').length;
              const scheduled = journeys.filter(j => !['active', 'landed', 'cancelled', 'diverted', 'incident'].includes(j.effectiveStatus)).length;

              return (
                <>
                  <span className="flex items-center gap-1.5 text-sm">
                    <span className="font-medium">{journeys.length}</span>
                    <span className="text-muted-foreground">journeys</span>
                  </span>
                  {inFlight > 0 && (
                    <span className="flex items-center gap-1.5 text-sm">
                      <span className="w-2 h-2 rounded-full bg-purple-500 animate-pulse" />
                      <span className="font-medium">{inFlight}</span>
                      <span className="text-muted-foreground">in flight</span>
                    </span>
                  )}
                  {connectionRisk > 0 && (
                    <span className="flex items-center gap-1.5 text-sm">
                      <span className="w-2 h-2 rounded-full bg-orange-500" />
                      <span className="font-medium text-orange-600 dark:text-orange-400">{connectionRisk}</span>
                      <span className="text-muted-foreground">at risk</span>
                    </span>
                  )}
                  {cancelled > 0 && (
                    <span className="flex items-center gap-1.5 text-sm">
                      <span className="w-2 h-2 rounded-full bg-red-500" />
                      <span className="font-medium text-red-600 dark:text-red-400">{cancelled}</span>
                      <span className="text-muted-foreground">cancelled</span>
                    </span>
                  )}
                  <span className="flex items-center gap-1.5 text-sm">
                    <span className="w-2 h-2 rounded-full bg-blue-500" />
                    <span className="font-medium">{scheduled}</span>
                    <span className="text-muted-foreground">scheduled</span>
                  </span>
                  <span className="flex items-center gap-1.5 text-sm">
                    <span className="w-2 h-2 rounded-full bg-emerald-500" />
                    <span className="font-medium">{landed}</span>
                    <span className="text-muted-foreground">landed</span>
                  </span>
                </>
              );
            })()}
          </div>
        )}

        {/* Upcoming journeys */}
        {upcomingJourneys.length > 0 ? (
          <div className="space-y-3">
            <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
              Active & Upcoming Journeys
            </h3>
            {upcomingJourneys.map((journey) => {
              const currentFlight = journey.flights[journey.currentSegmentIndex];
              const lastFlight = journey.flights[journey.flights.length - 1];
              const delay = Math.max(currentFlight?.arrivalDelay || 0, currentFlight?.departureDelay || 0);
              const routeChain = journey.flights.map(f => f.departureAirport).concat([lastFlight.arrivalAirport]).join(' → ');

              const borderColor = journey.hasLayoverRisk ? 'border-orange-500' :
                delay > 30 ? 'border-amber-500' :
                journey.effectiveStatus === 'active' ? 'border-purple-500' :
                journey.effectiveStatus === 'cancelled' ? 'border-red-500' :
                'border-indigo-500';

              return (
                <div
                  key={journey.vipId}
                  className={`border-l-4 ${borderColor} pl-4 py-2 hover:bg-accent transition-colors rounded-r`}
                >
                  <div className="flex justify-between items-start mb-1">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-foreground">{journey.vip?.name || 'Unknown'}</span>
                      {journey.isMultiSegment && (
                        <span className="text-xs text-muted-foreground">{journey.flights.length} legs</span>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      {journey.hasLayoverRisk && (
                        <span className="flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300">
                          <Link2 className="w-3 h-3" />
                          Connection risk
                        </span>
                      )}
                      {delay > 15 && (
                        <span className="flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300">
                          <AlertTriangle className="w-3 h-3" />
                          +{delay}min
                        </span>
                      )}
                      <span className={`px-2 py-0.5 text-xs rounded-full ${
                        journey.effectiveStatus === 'active' ? 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300' :
                        journey.effectiveStatus === 'landed' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
                        journey.effectiveStatus === 'cancelled' ? 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300' :
                        'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300'
                      }`}>
                        {journey.effectiveStatus}
                      </span>
                    </div>
                  </div>

                  {/* Route chain */}
                  <div className="text-xs text-muted-foreground mb-1">
                    {routeChain}
                    {currentFlight && (
                      <span className="ml-2 text-foreground/60">
                        {currentFlight.flightNumber}
                        {currentFlight.airlineName && ` · ${currentFlight.airlineName}`}
                      </span>
                    )}
                  </div>

                  {/* Progress bar for current segment */}
                  {currentFlight && <FlightProgressBar flight={currentFlight} compact />}

                  {/* Layover risk info */}
                  {journey.hasLayoverRisk && journey.layovers.filter(l => l.risk === 'warning' || l.risk === 'critical' || l.risk === 'missed').map((layover, idx) => (
                    <div key={idx} className={`flex items-center gap-1 mt-1 text-xs ${
                      layover.risk === 'missed' ? 'text-red-600 dark:text-red-400' :
                      layover.risk === 'critical' ? 'text-red-600 dark:text-red-400' :
                      'text-amber-600 dark:text-amber-400'
                    }`}>
                      <AlertTriangle className="w-3 h-3" />
                      {layover.airport}: {layover.risk === 'missed'
                        ? `Connection missed (${formatLayoverDuration(layover.effectiveMinutes)})`
                        : `Layover ${formatLayoverDuration(layover.effectiveMinutes)} (was ${formatLayoverDuration(layover.scheduledMinutes)})`
                      }
                    </div>
                  ))}

                  {/* Terminal/gate info for arriving current segment */}
                  {currentFlight && (currentFlight.arrivalTerminal || currentFlight.arrivalGate || currentFlight.arrivalBaggage) && (
                    <div className="flex gap-3 mt-1 text-xs text-muted-foreground">
                      {currentFlight.arrivalTerminal && <span>Terminal {currentFlight.arrivalTerminal}</span>}
                      {currentFlight.arrivalGate && <span>Gate {currentFlight.arrivalGate}</span>}
                      {currentFlight.arrivalBaggage && <span>Baggage {currentFlight.arrivalBaggage}</span>}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        ) : (
          <p className="text-sm text-muted-foreground text-center py-4">
            No upcoming flights tracked.
          </p>
        )}
      </div>

      {/* Upcoming Events */}
      <div className="bg-card shadow-medium rounded-lg p-6 border border-border">
        <h2 className="text-lg font-medium text-foreground mb-4">
          Upcoming Events
        </h2>
        {upcomingEvents.length > 0 ? (
          <div className="space-y-4">
            {upcomingEvents.map((event) => (
              <div
                key={event.id}
                className="border-l-4 border-primary pl-4 py-2 hover:bg-accent transition-colors rounded-r"
              >
                <div className="flex justify-between items-start">
                  <div>
                    <h3 className="text-sm font-medium text-foreground">
                      {event.title}
                    </h3>
                    <p className="text-sm text-muted-foreground">
                      {event.vips && event.vips.length > 0
                        ? event.vips.map(vip => vip.name).join(', ')
                        : 'No VIPs assigned'} • {event.driver?.name || 'No driver assigned'}
                    </p>
                    {event.location && (
                      <p className="text-xs text-muted-foreground mt-1">{event.location}</p>
                    )}
                  </div>
                  <div className="text-right">
                    <span className="text-xs text-muted-foreground block">
                      {formatDateTime(event.startTime)}
                    </span>
                    <span className={`inline-block mt-1 px-2 py-1 text-xs rounded-full ${
                      event.type === 'TRANSPORT' ? 'bg-blue-100 text-blue-800 dark:bg-blue-950 dark:text-blue-300' :
                      event.type === 'MEETING' ? 'bg-purple-100 text-purple-800 dark:bg-purple-950 dark:text-purple-300' :
                      event.type === 'MEAL' ? 'bg-green-100 text-green-800 dark:bg-green-950 dark:text-green-300' :
                      'bg-muted text-muted-foreground'
                    }`}>
                      {event.type}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-muted-foreground text-center py-4">
            No upcoming events scheduled.
          </p>
        )}
      </div>
    </div>
  );
}
