import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { X } from 'lucide-react';
import { api } from '@/lib/api';

interface FlightFormProps {
  flight?: Flight | null;
  onSubmit: (data: FlightFormData) => void;
  onCancel: () => void;
  isSubmitting: boolean;
}

interface Flight {
  id: string;
  vipId: string;
  flightNumber: string;
  flightDate: string;
  segment: number;
  departureAirport: string;
  arrivalAirport: string;
  scheduledDeparture: string | null;
  scheduledArrival: string | null;
  actualDeparture: string | null;
  actualArrival: string | null;
  status: string | null;
}

interface VIP {
  id: string;
  name: string;
  organization: string | null;
}

export interface FlightFormData {
  vipId: string;
  flightNumber: string;
  flightDate: string;
  segment?: number;
  departureAirport: string;
  arrivalAirport: string;
  scheduledDeparture?: string;
  scheduledArrival?: string;
  actualDeparture?: string;
  actualArrival?: string;
  status?: string;
}

export function FlightForm({ flight, onSubmit, onCancel, isSubmitting }: FlightFormProps) {
  // Helper to convert ISO datetime to datetime-local format
  const toDatetimeLocal = (isoString: string | null | undefined) => {
    if (!isoString) return '';
    const date = new Date(isoString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}`;
  };

  const toDateOnly = (isoString: string | null | undefined) => {
    if (!isoString) return '';
    const date = new Date(isoString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const [formData, setFormData] = useState<FlightFormData>({
    vipId: flight?.vipId || '',
    flightNumber: flight?.flightNumber || '',
    flightDate: toDateOnly(flight?.flightDate),
    segment: flight?.segment || 1,
    departureAirport: flight?.departureAirport || '',
    arrivalAirport: flight?.arrivalAirport || '',
    scheduledDeparture: toDatetimeLocal(flight?.scheduledDeparture),
    scheduledArrival: toDatetimeLocal(flight?.scheduledArrival),
    actualDeparture: toDatetimeLocal(flight?.actualDeparture),
    actualArrival: toDatetimeLocal(flight?.actualArrival),
    status: flight?.status || 'scheduled',
  });

  // Fetch VIPs for dropdown
  const { data: vips } = useQuery<VIP[]>({
    queryKey: ['vips'],
    queryFn: async () => {
      const { data } = await api.get('/vips');
      return data;
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    // Clean up the data - remove empty strings and convert datetimes to ISO
    const cleanedData: FlightFormData = {
      vipId: formData.vipId,
      flightNumber: formData.flightNumber,
      flightDate: new Date(formData.flightDate).toISOString(),
      segment: formData.segment,
      departureAirport: formData.departureAirport,
      arrivalAirport: formData.arrivalAirport,
      scheduledDeparture: formData.scheduledDeparture
        ? new Date(formData.scheduledDeparture).toISOString()
        : undefined,
      scheduledArrival: formData.scheduledArrival
        ? new Date(formData.scheduledArrival).toISOString()
        : undefined,
      actualDeparture: formData.actualDeparture
        ? new Date(formData.actualDeparture).toISOString()
        : undefined,
      actualArrival: formData.actualArrival
        ? new Date(formData.actualArrival).toISOString()
        : undefined,
      status: formData.status || undefined,
    };

    onSubmit(cleanedData);
  };

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    const { name, value, type } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === 'number' ? Number(value) : value,
    }));
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-card rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-6 border-b border-border">
          <h2 className="text-2xl font-bold text-foreground">
            {flight ? 'Edit Flight' : 'Add New Flight'}
          </h2>
          <button
            onClick={onCancel}
            className="text-muted-foreground hover:text-foreground"
          >
            <X className="h-6 w-6" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {/* VIP Selection */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">
              VIP *
            </label>
            <select
              name="vipId"
              required
              value={formData.vipId}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="">Select VIP</option>
              {vips?.map((vip) => (
                <option key={vip.id} value={vip.id}>
                  {vip.name} {vip.organization ? `(${vip.organization})` : ''}
                </option>
              ))}
            </select>
          </div>

          {/* Flight Number & Date */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Flight Number *
              </label>
              <input
                type="text"
                name="flightNumber"
                required
                value={formData.flightNumber}
                onChange={handleChange}
                placeholder="e.g., AA123"
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Flight Date *
              </label>
              <input
                type="date"
                name="flightDate"
                required
                value={formData.flightDate}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>
          </div>

          {/* Airports & Segment */}
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                From (IATA) *
              </label>
              <input
                type="text"
                name="departureAirport"
                required
                value={formData.departureAirport}
                onChange={handleChange}
                placeholder="JFK"
                maxLength={3}
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary uppercase"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                To (IATA) *
              </label>
              <input
                type="text"
                name="arrivalAirport"
                required
                value={formData.arrivalAirport}
                onChange={handleChange}
                placeholder="LAX"
                maxLength={3}
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary uppercase"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Segment
              </label>
              <input
                type="number"
                name="segment"
                min="1"
                value={formData.segment}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>
          </div>

          {/* Scheduled Times */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Scheduled Departure
              </label>
              <input
                type="datetime-local"
                name="scheduledDeparture"
                value={formData.scheduledDeparture}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Scheduled Arrival
              </label>
              <input
                type="datetime-local"
                name="scheduledArrival"
                value={formData.scheduledArrival}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>
          </div>

          {/* Actual Times */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Actual Departure
              </label>
              <input
                type="datetime-local"
                name="actualDeparture"
                value={formData.actualDeparture}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Actual Arrival
              </label>
              <input
                type="datetime-local"
                name="actualArrival"
                value={formData.actualArrival}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>
          </div>

          {/* Status */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">
              Status
            </label>
            <select
              name="status"
              value={formData.status}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="scheduled">Scheduled</option>
              <option value="boarding">Boarding</option>
              <option value="departed">Departed</option>
              <option value="en-route">En Route</option>
              <option value="landed">Landed</option>
              <option value="delayed">Delayed</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-4">
            <button
              type="submit"
              disabled={isSubmitting}
              className="flex-1 bg-primary text-white py-2 px-4 rounded-md hover:bg-primary/90 disabled:opacity-50"
            >
              {isSubmitting ? 'Saving...' : flight ? 'Update Flight' : 'Create Flight'}
            </button>
            <button
              type="button"
              onClick={onCancel}
              className="flex-1 bg-muted text-foreground py-2 px-4 rounded-md hover:bg-muted/80"
            >
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
