import { useMemo, useEffect, useState } from 'react';
import { Plane } from 'lucide-react';
import { Flight } from '@/types';
import { useFormattedDate } from '@/hooks/useFormattedDate';

interface FlightProgressBarProps {
  flight: Flight;
  compact?: boolean; // For mini version in dashboard/command center
}

function calculateProgress(flight: Flight): number {
  const status = flight.status?.toLowerCase();

  // Terminal states
  if (status === 'landed' || flight.actualArrival) return 100;
  if (status === 'cancelled' || status === 'diverted' || status === 'incident') return 0;

  // Not departed yet
  if (status === 'scheduled' || (!flight.actualDeparture && !status?.includes('active'))) {
    return 0;
  }

  // In flight - calculate based on time elapsed
  const departureTime = flight.actualDeparture || flight.estimatedDeparture || flight.scheduledDeparture;
  const arrivalTime = flight.estimatedArrival || flight.scheduledArrival;

  if (!departureTime || !arrivalTime) return status === 'active' ? 50 : 0;

  const now = Date.now();
  const dep = new Date(departureTime).getTime();
  const arr = new Date(arrivalTime).getTime();

  if (now <= dep) return 0;
  if (now >= arr) return 95; // Past ETA but not confirmed landed

  const totalDuration = arr - dep;
  const elapsed = now - dep;
  return Math.min(95, Math.max(5, Math.round((elapsed / totalDuration) * 100)));
}

function getTrackColor(flight: Flight): string {
  const status = flight.status?.toLowerCase();
  const delay = flight.arrivalDelay || flight.departureDelay || 0;

  if (status === 'cancelled') return 'bg-red-500';
  if (status === 'diverted' || status === 'incident') return 'bg-red-500';
  if (status === 'landed') return delay > 15 ? 'bg-amber-500' : 'bg-emerald-500';
  if (status === 'active') return delay > 15 ? 'bg-amber-500' : 'bg-purple-500';
  if (delay > 30) return 'bg-orange-500';
  if (delay > 15) return 'bg-amber-500';
  return 'bg-blue-500';
}

function getTrackBgColor(flight: Flight): string {
  const status = flight.status?.toLowerCase();
  if (status === 'cancelled') return 'bg-red-500/20';
  if (status === 'diverted' || status === 'incident') return 'bg-red-500/20';
  if (status === 'landed') return 'bg-emerald-500/20';
  if (status === 'active') return 'bg-purple-500/20';
  return 'bg-muted';
}

export function FlightProgressBar({ flight, compact = false }: FlightProgressBarProps) {
  const { formatTime } = useFormattedDate();
  const [progress, setProgress] = useState(() => calculateProgress(flight));
  const status = flight.status?.toLowerCase();
  const isActive = status === 'active';
  const isLanded = status === 'landed' || !!flight.actualArrival;
  const isCancelled = status === 'cancelled' || status === 'diverted' || status === 'incident';

  // Update progress periodically for active flights
  useEffect(() => {
    if (!isActive) {
      setProgress(calculateProgress(flight));
      return;
    }

    setProgress(calculateProgress(flight));
    const interval = setInterval(() => {
      setProgress(calculateProgress(flight));
    }, 30000); // Update every 30s for active flights

    return () => clearInterval(interval);
  }, [flight, isActive]);

  const trackColor = useMemo(() => getTrackColor(flight), [flight]);
  const trackBgColor = useMemo(() => getTrackBgColor(flight), [flight]);

  const departureTime = flight.actualDeparture || flight.estimatedDeparture || flight.scheduledDeparture;
  const arrivalTime = flight.actualArrival || flight.estimatedArrival || flight.scheduledArrival;
  const hasDelay = (flight.departureDelay || 0) > 0 || (flight.arrivalDelay || 0) > 0;

  if (compact) {
    return (
      <div className="w-full">
        <div className="flex items-center gap-2 text-xs">
          <span className="font-bold text-foreground">{flight.departureAirport}</span>
          <div className="flex-1 relative h-1.5 rounded-full overflow-hidden">
            <div className={`absolute inset-0 ${trackBgColor} rounded-full`} />
            <div
              className={`absolute inset-y-0 left-0 ${trackColor} rounded-full transition-all duration-1000`}
              style={{ width: `${progress}%` }}
            />
            {isActive && (
              <Plane
                className="absolute top-1/2 -translate-y-1/2 w-3 h-3 text-purple-500 transition-all duration-1000"
                style={{ left: `calc(${progress}% - 6px)` }}
              />
            )}
          </div>
          <span className="font-bold text-foreground">{flight.arrivalAirport}</span>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full py-2">
      {/* Airport codes and progress track */}
      <div className="flex items-center gap-3">
        {/* Departure airport */}
        <div className="text-center min-w-[48px]">
          <div className="text-lg font-bold text-foreground">{flight.departureAirport}</div>
        </div>

        {/* Progress track */}
        <div className="flex-1 relative">
          {/* Track background */}
          <div className={`h-2 rounded-full ${trackBgColor} relative overflow-visible`}>
            {/* Filled progress */}
            <div
              className={`absolute inset-y-0 left-0 rounded-full ${trackColor} transition-all duration-1000 ease-in-out`}
              style={{ width: `${progress}%` }}
            />

            {/* Departure dot */}
            <div className={`absolute left-0 top-1/2 -translate-y-1/2 -translate-x-1/2 w-3 h-3 rounded-full border-2 border-background ${progress > 0 ? trackColor : 'bg-muted-foreground/40'}`} />

            {/* Arrival dot */}
            <div className={`absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 w-3 h-3 rounded-full border-2 border-background ${progress >= 100 ? trackColor : 'bg-muted-foreground/40'}`} />

            {/* Airplane icon */}
            {!isCancelled && (
              <div
                className="absolute top-1/2 -translate-y-1/2 transition-all duration-1000 ease-in-out z-10"
                style={{ left: `${Math.max(2, Math.min(98, progress))}%`, transform: `translateX(-50%) translateY(-50%)` }}
              >
                <div className={`${isActive ? 'animate-bounce-subtle' : ''}`}>
                  <Plane
                    className={`w-5 h-5 ${
                      isLanded ? 'text-emerald-500' :
                      isActive ? 'text-purple-500' :
                      'text-muted-foreground'
                    } drop-shadow-sm`}
                    style={{ transform: 'rotate(0deg)' }}
                  />
                </div>
              </div>
            )}

            {/* Cancelled X */}
            {isCancelled && (
              <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-red-500 font-bold text-sm">
                &#x2715;
              </div>
            )}
          </div>
        </div>

        {/* Arrival airport */}
        <div className="text-center min-w-[48px]">
          <div className="text-lg font-bold text-foreground">{flight.arrivalAirport}</div>
        </div>
      </div>

      {/* Time and detail row */}
      <div className="flex justify-between mt-2 text-xs">
        {/* Departure details */}
        <div className="text-left">
          {departureTime && (
            <div className="flex items-center gap-1">
              {hasDelay && flight.scheduledDeparture && flight.scheduledDeparture !== departureTime ? (
                <>
                  <span className="line-through text-muted-foreground">{formatTime(flight.scheduledDeparture)}</span>
                  <span className="text-amber-600 dark:text-amber-400 font-medium">{formatTime(departureTime)}</span>
                </>
              ) : (
                <span className="text-muted-foreground">{formatTime(departureTime)}</span>
              )}
            </div>
          )}
          {(flight.departureTerminal || flight.departureGate) && (
            <div className="text-muted-foreground mt-0.5">
              {flight.departureTerminal && <span>T{flight.departureTerminal}</span>}
              {flight.departureTerminal && flight.departureGate && <span> </span>}
              {flight.departureGate && <span>Gate {flight.departureGate}</span>}
            </div>
          )}
        </div>

        {/* Center: flight duration or status */}
        <div className="text-center text-muted-foreground">
          {isActive && flight.aircraftType && (
            <span>{flight.aircraftType}</span>
          )}
          {isLanded && <span className="text-emerald-600 dark:text-emerald-400 font-medium">Landed</span>}
          {isCancelled && <span className="text-red-600 dark:text-red-400 font-medium capitalize">{status}</span>}
        </div>

        {/* Arrival details */}
        <div className="text-right">
          {arrivalTime && (
            <div className="flex items-center justify-end gap-1">
              {hasDelay && flight.scheduledArrival && flight.scheduledArrival !== arrivalTime ? (
                <>
                  <span className="line-through text-muted-foreground">{formatTime(flight.scheduledArrival)}</span>
                  <span className="text-amber-600 dark:text-amber-400 font-medium">{formatTime(arrivalTime)}</span>
                </>
              ) : (
                <span className="text-muted-foreground">
                  {isLanded ? '' : 'ETA '}{formatTime(arrivalTime)}
                </span>
              )}
            </div>
          )}
          {(flight.arrivalTerminal || flight.arrivalGate || flight.arrivalBaggage) && (
            <div className="text-muted-foreground mt-0.5">
              {flight.arrivalTerminal && <span>T{flight.arrivalTerminal}</span>}
              {flight.arrivalGate && <span> Gate {flight.arrivalGate}</span>}
              {flight.arrivalBaggage && <span> Bag {flight.arrivalBaggage}</span>}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
