import { useState } from 'react';
import {
  Plane,
  RefreshCw,
  Edit3,
  Trash2,
  AlertTriangle,
  Clock,
  ChevronDown,
  ChevronUp,
  Users,
  CheckCircle,
  Link2,
  XCircle,
} from 'lucide-react';
import { Flight, Journey, Layover } from '@/types';
import { FlightProgressBar } from './FlightProgressBar';
import { useRefreshFlight } from '@/hooks/useFlights';
import { formatLayoverDuration } from '@/lib/journeyUtils';
import { useFormattedDate } from '@/hooks/useFormattedDate';

interface FlightCardProps {
  flight?: Flight;
  journey?: Journey;
  onEdit?: (flight: Flight) => void;
  onDelete?: (flight: Flight) => void;
}

function getStatusDotColor(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 'bg-emerald-500';
  if (status === 'active') return delay > 15 ? 'bg-amber-500 animate-pulse' : 'bg-purple-500 animate-pulse';
  if (delay > 30) return 'bg-orange-500';
  if (delay > 15) return 'bg-amber-500';
  return 'bg-blue-500';
}

function getAlertBanner(flight: Flight): { message: string; color: string } | null {
  const status = flight.status?.toLowerCase();
  const delay = Math.max(flight.arrivalDelay || 0, flight.departureDelay || 0);

  if (status === 'cancelled') return { message: 'FLIGHT CANCELLED', color: 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-400' };
  if (status === 'diverted') return { message: 'FLIGHT DIVERTED', color: 'bg-orange-500/10 border-orange-500/30 text-orange-700 dark:text-orange-400' };
  if (status === 'incident') return { message: 'INCIDENT REPORTED', color: 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-400' };
  if (delay > 60) return { message: `DELAYED ${delay} MINUTES`, color: 'bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-400' };
  if (delay > 30) return { message: `Delayed ${delay} min`, color: 'bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-400' };
  return null;
}

function formatRelativeTime(isoString: string | null): string {
  if (!isoString) return 'Never';
  const diff = Date.now() - new Date(isoString).getTime();
  const minutes = Math.floor(diff / 60000);
  if (minutes < 1) return 'Just now';
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  return `${Math.floor(hours / 24)}d ago`;
}

function getSegmentStatusIcon(flight: Flight) {
  const status = flight.status?.toLowerCase();
  if (status === 'landed' || flight.actualArrival) {
    return <CheckCircle className="w-3.5 h-3.5 text-emerald-500" />;
  }
  if (status === 'active') {
    return <Plane className="w-3.5 h-3.5 text-purple-500" />;
  }
  if (status === 'cancelled' || status === 'diverted') {
    return <XCircle className="w-3.5 h-3.5 text-red-500" />;
  }
  return <Clock className="w-3.5 h-3.5 text-muted-foreground" />;
}

function LayoverRow({ layover }: { layover: Layover }) {
  const riskColors = {
    none: 'text-muted-foreground',
    ok: 'text-muted-foreground',
    warning: 'bg-amber-50 dark:bg-amber-950/20 text-amber-700 dark:text-amber-400',
    critical: 'bg-red-50 dark:bg-red-950/20 text-red-700 dark:text-red-400',
    missed: 'bg-red-100 dark:bg-red-950/30 text-red-800 dark:text-red-300',
  };

  const isBadge = layover.risk === 'warning' || layover.risk === 'critical' || layover.risk === 'missed';

  return (
    <div className={`flex items-center gap-2 px-4 py-1.5 text-xs ${isBadge ? riskColors[layover.risk] : ''}`}>
      <div className="flex items-center gap-1.5 ml-6">
        <div className="w-px h-3 bg-border" />
        <Link2 className="w-3 h-3 text-muted-foreground/50" />
      </div>
      <div className="flex items-center gap-2 flex-1">
        <span className={isBadge ? 'font-medium' : 'text-muted-foreground'}>
          {layover.risk === 'missed' ? (
            <>CONNECTION MISSED at {layover.airport} - arrived {formatLayoverDuration(layover.effectiveMinutes)}</>
          ) : (
            <>{formatLayoverDuration(layover.scheduledMinutes)} layover at {layover.airport}</>
          )}
        </span>
        {layover.risk === 'warning' && layover.effectiveMinutes !== layover.scheduledMinutes && (
          <span className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-800 dark:text-amber-300 text-[10px] font-semibold">
            <AlertTriangle className="w-2.5 h-2.5" />
            now {formatLayoverDuration(layover.effectiveMinutes)}
          </span>
        )}
        {layover.risk === 'critical' && (
          <span className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300 text-[10px] font-semibold">
            <AlertTriangle className="w-2.5 h-2.5" />
            only {formatLayoverDuration(layover.effectiveMinutes)} remaining
          </span>
        )}
      </div>
    </div>
  );
}

// ============================================================
// SINGLE FLIGHT CARD (original behavior)
// ============================================================

function SingleFlightCard({ flight, onEdit, onDelete }: { flight: Flight; onEdit?: (f: Flight) => void; onDelete?: (f: Flight) => void }) {
  const [expanded, setExpanded] = useState(false);
  const refreshMutation = useRefreshFlight();
  const alert = getAlertBanner(flight);
  const dotColor = getStatusDotColor(flight);
  const { formatDateTime } = useFormattedDate();

  return (
    <div className="bg-card border border-border rounded-lg shadow-soft overflow-hidden transition-shadow hover:shadow-medium">
      {alert && (
        <div className={`px-4 py-1.5 text-xs font-semibold border-b flex items-center gap-2 ${alert.color}`}>
          <AlertTriangle className="w-3.5 h-3.5" />
          {alert.message}
        </div>
      )}

      <div className="px-4 pt-3 pb-1">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <div className={`w-2.5 h-2.5 rounded-full ${dotColor}`} />
            <div className="flex items-center gap-2">
              <span className="font-bold text-foreground">{flight.flightNumber}</span>
              {flight.airlineName && (
                <span className="text-xs text-muted-foreground">{flight.airlineName}</span>
              )}
            </div>
            {flight.vip && (
              <div className="flex items-center gap-1 text-sm text-muted-foreground">
                <span className="text-muted-foreground/50">|</span>
                <span className="font-medium text-foreground/80">{flight.vip.name}</span>
                {flight.vip.partySize > 1 && (
                  <span className="flex items-center gap-0.5 text-xs text-muted-foreground">
                    <Users className="w-3 h-3" />
                    +{flight.vip.partySize - 1}
                  </span>
                )}
              </div>
            )}
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={() => refreshMutation.mutate(flight.id)}
              disabled={refreshMutation.isPending}
              className="p-1.5 rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50"
              title="Refresh from API"
            >
              <RefreshCw className={`w-4 h-4 ${refreshMutation.isPending ? 'animate-spin' : ''}`} />
            </button>
            {onEdit && (
              <button onClick={() => onEdit(flight)} className="p-1.5 rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground" title="Edit flight">
                <Edit3 className="w-4 h-4" />
              </button>
            )}
            {onDelete && (
              <button onClick={() => onDelete(flight)} className="p-1.5 rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-red-500" title="Delete flight">
                <Trash2 className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>
      </div>

      <div className="px-4">
        <FlightProgressBar flight={flight} />
      </div>

      <div className="px-4 pb-2">
        <button
          onClick={() => setExpanded(!expanded)}
          className="w-full flex items-center justify-between py-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
        >
          <div className="flex items-center gap-3">
            <span className="flex items-center gap-1">
              <Clock className="w-3 h-3" />
              Updated {formatRelativeTime(flight.lastPolledAt)}
            </span>
            {flight.pollCount > 0 && (
              <span>{flight.pollCount} poll{flight.pollCount !== 1 ? 's' : ''}</span>
            )}
            <span className="px-1.5 py-0.5 rounded bg-muted text-[10px] uppercase tracking-wider font-medium">
              {flight.trackingPhase.replace(/_/g, ' ')}
            </span>
          </div>
          {expanded ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
        </button>

        {expanded && (
          <div className="pt-2 pb-1 border-t border-border/50 space-y-2 text-xs">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="font-medium text-foreground mb-1">Departure</div>
                <div className="space-y-0.5 text-muted-foreground">
                  {flight.scheduledDeparture && <div>Scheduled: {formatDateTime(flight.scheduledDeparture)}</div>}
                  {flight.estimatedDeparture && <div>Estimated: {formatDateTime(flight.estimatedDeparture)}</div>}
                  {flight.actualDeparture && <div className="text-foreground">Actual: {formatDateTime(flight.actualDeparture)}</div>}
                  {flight.departureDelay != null && flight.departureDelay > 0 && (
                    <div className="text-amber-600 dark:text-amber-400">Delay: {flight.departureDelay} min</div>
                  )}
                  {flight.departureTerminal && <div>Terminal: {flight.departureTerminal}</div>}
                  {flight.departureGate && <div>Gate: {flight.departureGate}</div>}
                </div>
              </div>
              <div>
                <div className="font-medium text-foreground mb-1">Arrival</div>
                <div className="space-y-0.5 text-muted-foreground">
                  {flight.scheduledArrival && <div>Scheduled: {formatDateTime(flight.scheduledArrival)}</div>}
                  {flight.estimatedArrival && <div>Estimated: {formatDateTime(flight.estimatedArrival)}</div>}
                  {flight.actualArrival && <div className="text-foreground">Actual: {formatDateTime(flight.actualArrival)}</div>}
                  {flight.arrivalDelay != null && flight.arrivalDelay > 0 && (
                    <div className="text-amber-600 dark:text-amber-400">Delay: {flight.arrivalDelay} min</div>
                  )}
                  {flight.arrivalTerminal && <div>Terminal: {flight.arrivalTerminal}</div>}
                  {flight.arrivalGate && <div>Gate: {flight.arrivalGate}</div>}
                  {flight.arrivalBaggage && <div>Baggage: {flight.arrivalBaggage}</div>}
                </div>
              </div>
            </div>
            {flight.aircraftType && (
              <div className="text-muted-foreground">Aircraft: {flight.aircraftType}</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================================
// MULTI-SEGMENT JOURNEY CARD
// ============================================================

function JourneyCard({ journey, onEdit, onDelete }: { journey: Journey; onEdit?: (f: Flight) => void; onDelete?: (f: Flight) => void }) {
  const [expandedSeg, setExpandedSeg] = useState<number | null>(null);
  const refreshMutation = useRefreshFlight();
  const currentFlight = journey.flights[journey.currentSegmentIndex];
  const dotColor = getStatusDotColor(currentFlight);
  const vip = journey.vip || currentFlight?.vip;
  const { formatDateTime } = useFormattedDate();

  // Route chain: BWI -> ORD -> SLC
  const routeChain = [journey.origin, ...journey.flights.slice(1).map(f => f.departureAirport), journey.destination]
    .filter((v, i, a) => a.indexOf(v) === i); // dedupe

  // Connection risk banner
  const worstLayover = journey.layovers.reduce<Layover | null>((worst, l) => {
    if (!worst) return l;
    if (l.risk === 'missed') return l;
    if (l.risk === 'critical' && worst.risk !== 'missed') return l;
    if (l.risk === 'warning' && worst.risk !== 'missed' && worst.risk !== 'critical') return l;
    return worst;
  }, null);

  const connectionBanner = worstLayover && (worstLayover.risk === 'warning' || worstLayover.risk === 'critical' || worstLayover.risk === 'missed')
    ? {
        message: worstLayover.risk === 'missed'
          ? `CONNECTION MISSED at ${worstLayover.airport}`
          : worstLayover.risk === 'critical'
          ? `CONNECTION AT RISK - only ${formatLayoverDuration(worstLayover.effectiveMinutes)} at ${worstLayover.airport}`
          : `Connection tight - ${formatLayoverDuration(worstLayover.effectiveMinutes)} at ${worstLayover.airport}`,
        color: worstLayover.risk === 'missed'
          ? 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-400'
          : worstLayover.risk === 'critical'
          ? 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-400'
          : 'bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-400',
      }
    : null;

  return (
    <div className="bg-card border border-border rounded-lg shadow-soft overflow-hidden transition-shadow hover:shadow-medium">
      {/* Connection risk banner */}
      {connectionBanner && (
        <div className={`px-4 py-1.5 text-xs font-semibold border-b flex items-center gap-2 ${connectionBanner.color}`}>
          <AlertTriangle className="w-3.5 h-3.5" />
          {connectionBanner.message}
        </div>
      )}

      {/* Journey header */}
      <div className="px-4 pt-3 pb-2">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <div className={`w-2.5 h-2.5 rounded-full ${dotColor}`} />
            {vip && (
              <div className="flex items-center gap-1.5">
                <span className="font-bold text-foreground">{vip.name}</span>
                {vip.partySize > 1 && (
                  <span className="flex items-center gap-0.5 text-xs text-muted-foreground">
                    <Users className="w-3 h-3" />
                    +{vip.partySize - 1}
                  </span>
                )}
              </div>
            )}
          </div>
          {/* Route chain */}
          <div className="flex items-center gap-1 text-xs text-muted-foreground">
            {routeChain.map((code, i) => (
              <span key={i} className="flex items-center gap-1">
                {i > 0 && <span className="text-muted-foreground/40">{'→'}</span>}
                <span className={i === 0 || i === routeChain.length - 1 ? 'font-bold text-foreground' : ''}>{code}</span>
              </span>
            ))}
            <span className="ml-1 px-1.5 py-0.5 rounded bg-muted text-[10px] uppercase tracking-wider font-medium">
              {journey.flights.length} legs
            </span>
          </div>
        </div>
      </div>

      {/* Segment stack */}
      {journey.flights.map((seg, i) => {
        const isExpanded = expandedSeg === i;
        const isCurrent = i === journey.currentSegmentIndex;

        return (
          <div key={seg.id}>
            {/* Layover row between segments */}
            {i > 0 && journey.layovers[i - 1] && (
              <LayoverRow layover={journey.layovers[i - 1]} />
            )}

            {/* Segment row */}
            <div className={`px-4 py-2 ${isCurrent ? 'bg-accent/30' : ''}`}>
              <div className="flex items-center gap-2">
                {/* Leg label + status icon */}
                <div className="flex items-center gap-1.5 min-w-[60px]">
                  <span className="text-[10px] font-semibold text-muted-foreground uppercase">Leg {i + 1}</span>
                  {getSegmentStatusIcon(seg)}
                </div>

                {/* Compact progress bar */}
                <div className="flex-1">
                  <FlightProgressBar flight={seg} compact />
                </div>

                {/* Flight number + actions */}
                <div className="flex items-center gap-1.5 flex-shrink-0">
                  <span className="text-xs font-medium text-muted-foreground">{seg.flightNumber}</span>
                  <button
                    onClick={() => refreshMutation.mutate(seg.id)}
                    disabled={refreshMutation.isPending}
                    className="p-1 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50"
                    title="Refresh"
                  >
                    <RefreshCw className={`w-3 h-3 ${refreshMutation.isPending ? 'animate-spin' : ''}`} />
                  </button>
                  <button
                    onClick={() => setExpandedSeg(isExpanded ? null : i)}
                    className="p-1 rounded hover:bg-accent transition-colors text-muted-foreground"
                  >
                    {isExpanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
                  </button>
                </div>
              </div>

              {/* Terminal/gate info for current segment */}
              {isCurrent && (seg.arrivalTerminal || seg.arrivalGate || seg.arrivalBaggage) && (
                <div className="flex gap-3 mt-1 ml-[68px] text-[10px] text-muted-foreground">
                  {seg.arrivalTerminal && <span>Terminal {seg.arrivalTerminal}</span>}
                  {seg.arrivalGate && <span>Gate {seg.arrivalGate}</span>}
                  {seg.arrivalBaggage && <span>Baggage {seg.arrivalBaggage}</span>}
                </div>
              )}

              {/* Expanded details */}
              {isExpanded && (
                <div className="mt-2 pt-2 border-t border-border/50 text-xs">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="font-medium text-foreground mb-1">Departure</div>
                      <div className="space-y-0.5 text-muted-foreground">
                        {seg.scheduledDeparture && <div>Scheduled: {formatDateTime(seg.scheduledDeparture)}</div>}
                        {seg.actualDeparture && <div className="text-foreground">Actual: {formatDateTime(seg.actualDeparture)}</div>}
                        {seg.departureDelay != null && seg.departureDelay > 0 && (
                          <div className="text-amber-600 dark:text-amber-400">Delay: {seg.departureDelay} min</div>
                        )}
                        {seg.departureTerminal && <div>Terminal: {seg.departureTerminal}</div>}
                        {seg.departureGate && <div>Gate: {seg.departureGate}</div>}
                      </div>
                    </div>
                    <div>
                      <div className="font-medium text-foreground mb-1">Arrival</div>
                      <div className="space-y-0.5 text-muted-foreground">
                        {seg.scheduledArrival && <div>Scheduled: {formatDateTime(seg.scheduledArrival)}</div>}
                        {seg.actualArrival && <div className="text-foreground">Actual: {formatDateTime(seg.actualArrival)}</div>}
                        {seg.arrivalDelay != null && seg.arrivalDelay > 0 && (
                          <div className="text-amber-600 dark:text-amber-400">Delay: {seg.arrivalDelay} min</div>
                        )}
                        {seg.arrivalTerminal && <div>Terminal: {seg.arrivalTerminal}</div>}
                        {seg.arrivalGate && <div>Gate: {seg.arrivalGate}</div>}
                        {seg.arrivalBaggage && <div>Baggage: {seg.arrivalBaggage}</div>}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 mt-2">
                    {onEdit && (
                      <button onClick={() => onEdit(seg)} className="text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400">Edit</button>
                    )}
                    {onDelete && (
                      <button onClick={() => onDelete(seg)} className="text-xs text-red-600 hover:text-red-800 dark:text-red-400">Delete</button>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        );
      })}

      {/* Footer */}
      <div className="px-4 py-1.5 border-t border-border/50 text-xs text-muted-foreground flex items-center gap-3">
        <span className="flex items-center gap-1">
          <Clock className="w-3 h-3" />
          Updated {formatRelativeTime(currentFlight?.lastPolledAt)}
        </span>
        <span className="px-1.5 py-0.5 rounded bg-muted text-[10px] uppercase tracking-wider font-medium">
          {journey.effectiveStatus}
        </span>
      </div>
    </div>
  );
}

// ============================================================
// EXPORT: Routes to single or journey card
// ============================================================

export function FlightCard({ flight, journey, onEdit, onDelete }: FlightCardProps) {
  if (journey) {
    // Multi-segment journeys always use JourneyCard, single-segment journeys too when passed as journey
    if (journey.isMultiSegment) {
      return <JourneyCard journey={journey} onEdit={onEdit} onDelete={onDelete} />;
    }
    // Single-segment journey: render as single flight card
    return <SingleFlightCard flight={journey.flights[0]} onEdit={onEdit} onDelete={onDelete} />;
  }

  if (flight) {
    return <SingleFlightCard flight={flight} onEdit={onEdit} onDelete={onDelete} />;
  }

  return null;
}
