import { useState, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { useQuery } from '@tanstack/react-query';
import { X, AlertTriangle, Users, Car, Link2 } from 'lucide-react';
import { api } from '@/lib/api';
import { ScheduleEvent, VIP, Driver, Vehicle } from '@/types';
import { useFormattedDate } from '@/hooks/useFormattedDate';
import { toDatetimeLocal } from '@/lib/utils';
import { EVENT_TYPE_LABELS, EVENT_STATUS_LABELS } from '@/lib/enum-labels';
import { queryKeys } from '@/lib/query-keys';

interface EventFormProps {
  event?: ScheduleEvent | null;
  onSubmit: (data: EventFormData) => void;
  onCancel: () => void;
  isSubmitting: boolean;
  extraActions?: React.ReactNode;
}

export interface EventFormData {
  vipIds: string[];
  title: string;
  location?: string;
  pickupLocation?: string;
  dropoffLocation?: string;
  startTime: string;
  endTime: string;
  description?: string;
  type: string;
  status: string;
  driverId?: string;
  vehicleId?: string;
  masterEventId?: string;
  forceAssign?: boolean;
}

interface ScheduleConflict {
  id: string;
  title: string;
  startTime: string;
  endTime: string;
}

export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraActions }: EventFormProps) {
  const { formatDateTime } = useFormattedDate();

  const [formData, setFormData] = useState<EventFormData>({
    vipIds: event?.vipIds || [],
    title: event?.title || '',
    location: event?.location || '',
    pickupLocation: event?.pickupLocation || '',
    dropoffLocation: event?.dropoffLocation || '',
    startTime: toDatetimeLocal(event?.startTime),
    endTime: toDatetimeLocal(event?.endTime),
    description: event?.description || '',
    type: event?.type || 'TRANSPORT',
    status: event?.status || 'SCHEDULED',
    driverId: event?.driverId || '',
    vehicleId: event?.vehicleId || '',
    masterEventId: event?.masterEventId || '',
  });

  const [showConflictDialog, setShowConflictDialog] = useState(false);
  const [conflicts, setConflicts] = useState<ScheduleConflict[]>([]);
  const [showCapacityWarning, setShowCapacityWarning] = useState(false);
  const [capacityExceeded, setCapacityExceeded] = useState<{capacity: number, requested: number} | null>(null);
  const [pendingData, setPendingData] = useState<EventFormData | null>(null);

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

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

  // Fetch Vehicles for dropdown
  const { data: vehicles } = useQuery<Vehicle[]>({
    queryKey: queryKeys.vehicles.all,
    queryFn: async () => {
      const { data } = await api.get('/vehicles');
      return data;
    },
  });

  // Fetch all events (for master event selector)
  const { data: allEvents } = useQuery<ScheduleEvent[]>({
    queryKey: queryKeys.events.all,
    queryFn: async () => {
      const { data } = await api.get('/events');
      return data;
    },
  });

  // Filter to itinerary items (non-transport events) for master event dropdown
  const masterEventOptions = useMemo(() => {
    if (!allEvents) return [];
    return allEvents.filter(e =>
      e.type !== 'TRANSPORT' &&
      e.status !== 'CANCELLED' &&
      e.id !== event?.id // Exclude self
    );
  }, [allEvents, event?.id]);

  // Get selected vehicle capacity (using party sizes)
  const selectedVehicle = vehicles?.find(v => v.id === formData.vehicleId);
  const seatsUsed = vips
    ?.filter(v => formData.vipIds.includes(v.id))
    .reduce((sum, v) => sum + (v.partySize || 1), 0) || 0;
  const seatsAvailable = selectedVehicle ? selectedVehicle.seatCapacity : 0;

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

    // Clean up the data
    const cleanedData: EventFormData = {
      ...formData,
      startTime: new Date(formData.startTime).toISOString(),
      endTime: new Date(formData.endTime).toISOString(),
      location: formData.location || undefined,
      pickupLocation: formData.pickupLocation || undefined,
      dropoffLocation: formData.dropoffLocation || undefined,
      description: formData.description || undefined,
      driverId: formData.driverId || undefined,
      vehicleId: formData.vehicleId || undefined,
      masterEventId: formData.masterEventId || undefined,
    };

    // Store for potential retry
    setPendingData(cleanedData);

    // Submit directly
    handleActualSubmit(cleanedData);
  };

  const handleActualSubmit = async (data: EventFormData) => {
    try {
      await onSubmit(data);
      // Success handled by parent component
    } catch (error: any) {
      console.error('[EVENT_FORM] Submit failed:', error);

      // Check for conflict error
      if (error.response?.data?.conflicts) {
        setConflicts(error.response.data.conflicts);
        setShowConflictDialog(true);
        return;
      }

      // Check for capacity error
      if (error.response?.data?.exceeded) {
        setCapacityExceeded({
          capacity: error.response.data.capacity,
          requested: error.response.data.requested,
        });
        setShowCapacityWarning(true);
        return;
      }

      // Other errors are shown via toast by parent
    }
  };

  const handleForceSubmit = () => {
    if (pendingData) {
      const dataWithForce = { ...pendingData, forceAssign: true };
      setShowConflictDialog(false);
      setShowCapacityWarning(false);
      handleActualSubmit(dataWithForce);
    }
  };

  const handleCancelConflict = () => {
    setShowConflictDialog(false);
    setShowCapacityWarning(false);
    setPendingData(null);
    setConflicts([]);
    setCapacityExceeded(null);
  };

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

  const handleVipToggle = (vipId: string) => {
    setFormData((prev) => {
      const isSelected = prev.vipIds.includes(vipId);
      return {
        ...prev,
        vipIds: isSelected
          ? prev.vipIds.filter(id => id !== vipId)
          : [...prev.vipIds, vipId],
      };
    });
  };

  const selectedVipNames = useMemo(() => {
    return vips
      ?.filter(vip => formData.vipIds.includes(vip.id))
      .map(vip => vip.partySize > 1 ? `${vip.name} (+${vip.partySize - 1})` : vip.name)
      .join(', ') || 'None selected';
  }, [vips, formData.vipIds]);

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

          <form onSubmit={handleSubmit} className="p-6 space-y-4">
            {/* Master Event Selector (link transport to itinerary item) */}
            {formData.type === 'TRANSPORT' && masterEventOptions.length > 0 && (
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  <Link2 className="inline h-4 w-4 mr-1" />
                  Linked Itinerary Item (optional)
                </label>
                <select
                  name="masterEventId"
                  value={formData.masterEventId}
                  onChange={(e) => {
                    const selectedId = e.target.value;
                    setFormData(prev => ({ ...prev, masterEventId: selectedId }));
                    // Auto-fill VIPs from the selected master event
                    if (selectedId) {
                      const masterEvent = allEvents?.find(ev => ev.id === selectedId);
                      if (masterEvent?.vipIds && masterEvent.vipIds.length > 0) {
                        setFormData(prev => ({ ...prev, masterEventId: selectedId, vipIds: masterEvent.vipIds }));
                      }
                    }
                  }}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                >
                  <option value="">No linked event</option>
                  {masterEventOptions.map(ev => (
                    <option key={ev.id} value={ev.id}>
                      {ev.title} ({ev.type}) — {formatDateTime(ev.startTime)}
                    </option>
                  ))}
                </select>
                <p className="mt-1 text-xs text-muted-foreground">
                  Link this transport to a shared activity. VIPs will auto-populate from the linked event.
                </p>
              </div>
            )}

            {/* VIP Multi-Select */}
            <div>
              <label className="block text-sm font-medium text-foreground mb-2">
                <Users className="inline h-4 w-4 mr-1" />
                VIPs * (select one or more)
              </label>

              <div className="border border-input rounded-md p-3 max-h-48 overflow-y-auto bg-background">
                {vips?.map((vip) => (
                  <label
                    key={vip.id}
                    className="flex items-center py-2 px-3 hover:bg-accent rounded cursor-pointer"
                    style={{ minHeight: '44px' }}
                  >
                    <input
                      type="checkbox"
                      checked={formData.vipIds.includes(vip.id)}
                      onChange={() => handleVipToggle(vip.id)}
                      className="h-4 w-4 text-primary rounded border-input focus:ring-primary"
                    />
                    <span className="ml-3 text-base text-foreground">
                      {vip.name}
                      {vip.partySize > 1 && (
                        <span className="text-xs text-blue-600 dark:text-blue-400 ml-1.5 font-medium">+{vip.partySize - 1}</span>
                      )}
                      {vip.organization && (
                        <span className="text-sm text-muted-foreground ml-2">({vip.organization})</span>
                      )}
                    </span>
                  </label>
                ))}
              </div>

              <div className="mt-2 text-sm text-muted-foreground">
                <strong>Selected ({formData.vipIds.length}):</strong> {selectedVipNames}
              </div>
            </div>

            {/* Title */}
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Event Title *
              </label>
              <input
                type="text"
                name="title"
                required
                value={formData.title}
                onChange={handleChange}
                placeholder="e.g., Transport to Campfire Night"
                className="w-full px-3 py-2 bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>

            {/* Pickup & Dropoff Locations */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Pickup Location
                </label>
                <input
                  type="text"
                  name="pickupLocation"
                  value={formData.pickupLocation}
                  onChange={handleChange}
                  placeholder="e.g., Grand Hotel Lobby"
                  className="w-full px-3 py-2 bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Dropoff Location
                </label>
                <input
                  type="text"
                  name="dropoffLocation"
                  value={formData.dropoffLocation}
                  onChange={handleChange}
                  placeholder="e.g., Camp Amphitheater"
                  className="w-full px-3 py-2 bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>
            </div>

            {/* Start & End Time */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Start Time *
                </label>
                <input
                  type="datetime-local"
                  name="startTime"
                  required
                  value={formData.startTime}
                  onChange={handleChange}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  End Time *
                </label>
                <input
                  type="datetime-local"
                  name="endTime"
                  required
                  value={formData.endTime}
                  onChange={handleChange}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>
            </div>

            {/* Vehicle Selection with Capacity */}
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                <Car className="inline h-4 w-4 mr-1" />
                Assigned Vehicle
              </label>
              <select
                name="vehicleId"
                value={formData.vehicleId}
                onChange={handleChange}
                className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              >
                <option value="">No vehicle assigned</option>
                {vehicles?.map((vehicle) => (
                  <option key={vehicle.id} value={vehicle.id}>
                    {vehicle.name} ({vehicle.type}, {vehicle.seatCapacity} seats)
                  </option>
                ))}
              </select>
              {selectedVehicle && (
                <div className={`mt-2 text-sm ${seatsUsed > seatsAvailable ? 'text-red-600 font-medium' : 'text-muted-foreground'}`}>
                  Capacity: {seatsUsed}/{seatsAvailable} seats (incl. entourage)
                  {seatsUsed > seatsAvailable && ' — OVER CAPACITY'}
                </div>
              )}
            </div>

            {/* Driver Selection */}
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Assigned Driver
              </label>
              <select
                name="driverId"
                value={formData.driverId}
                onChange={handleChange}
                className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              >
                <option value="">No driver assigned</option>
                {drivers?.map((driver) => (
                  <option key={driver.id} value={driver.id}>
                    {driver.name} ({driver.phone})
                  </option>
                ))}
              </select>
            </div>

            {/* Event Type & Status */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Event Type *
                </label>
                <select
                  name="type"
                  required
                  value={formData.type}
                  onChange={handleChange}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                >
                  {Object.entries(EVENT_TYPE_LABELS).map(([value, label]) => (
                    <option key={value} value={value}>
                      {label}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Status *
                </label>
                <select
                  name="status"
                  required
                  value={formData.status}
                  onChange={handleChange}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                >
                  {Object.entries(EVENT_STATUS_LABELS).map(([value, label]) => (
                    <option key={value} value={value}>
                      {label}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Description */}
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                Description
              </label>
              <textarea
                name="description"
                value={formData.description}
                onChange={handleChange}
                rows={3}
                placeholder="Additional notes or instructions"
                className="w-full px-3 py-2 bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>

            {/* Actions */}
            <div className="flex gap-3 pt-4">
              <button
                type="submit"
                disabled={isSubmitting || formData.vipIds.length === 0}
                className="flex-1 bg-primary text-white py-2 px-4 rounded-md hover:bg-primary/90 disabled:opacity-50"
                style={{ minHeight: '44px' }}
              >
                {isSubmitting ? 'Saving...' : event ? 'Update Event' : 'Create Event'}
              </button>
              <button
                type="button"
                onClick={onCancel}
                className="flex-1 bg-muted text-foreground py-2 px-4 rounded-md hover:bg-muted/80"
                style={{ minHeight: '44px' }}
              >
                Cancel
              </button>
            </div>

            {/* Extra Actions (e.g., Cancel Event, Delete Event) */}
            {extraActions}
          </form>
        </div>
      </div>

      {/* Conflict Dialog */}
      {showConflictDialog && createPortal(
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-[60]">
          <div className="bg-card rounded-lg shadow-xl w-full max-w-2xl mx-4">
            <div className="p-6">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0">
                  <div className="w-12 h-12 rounded-full bg-yellow-100 flex items-center justify-center">
                    <AlertTriangle className="h-6 w-6 text-yellow-600" />
                  </div>
                </div>
                <div className="flex-1">
                  <h3 className="text-lg font-semibold text-foreground mb-2">
                    Scheduling Conflict Detected
                  </h3>
                  <p className="text-base text-muted-foreground mb-4">
                    This driver already has {conflicts.length} conflicting event{conflicts.length > 1 ? 's' : ''} scheduled during this time:
                  </p>

                  <div className="space-y-2 mb-6">
                    {conflicts.map((conflict) => (
                      <div
                        key={conflict.id}
                        className="bg-yellow-50 border border-yellow-200 rounded-md p-4"
                      >
                        <div className="font-medium text-gray-900">{conflict.title}</div>
                        <div className="text-sm text-gray-600 mt-1">
                          {formatDateTime(conflict.startTime)} - {formatDateTime(conflict.endTime)}
                        </div>
                      </div>
                    ))}
                  </div>

                  <p className="text-base text-foreground font-medium mb-6">
                    Do you want to proceed with this assignment anyway?
                  </p>

                  <div className="flex gap-3">
                    <button
                      onClick={handleCancelConflict}
                      className="flex-1 px-4 py-3 border border-input rounded-md text-base font-medium text-foreground hover:bg-accent"
                      style={{ minHeight: '44px' }}
                    >
                      Cancel
                    </button>
                    <button
                      onClick={handleForceSubmit}
                      disabled={isSubmitting}
                      className="flex-1 px-4 py-3 bg-yellow-600 text-white rounded-md text-base font-medium hover:bg-yellow-700 disabled:opacity-50"
                      style={{ minHeight: '44px' }}
                    >
                      {isSubmitting ? 'Saving...' : 'Assign Anyway'}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* Capacity Warning Dialog */}
      {showCapacityWarning && capacityExceeded && createPortal(
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-[60]">
          <div className="bg-card rounded-lg shadow-xl w-full max-w-md mx-4">
            <div className="p-6">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0">
                  <div className="w-12 h-12 rounded-full bg-orange-100 flex items-center justify-center">
                    <AlertTriangle className="h-6 w-6 text-orange-600" />
                  </div>
                </div>
                <div className="flex-1">
                  <h3 className="text-lg font-semibold text-foreground mb-2">
                    Vehicle Capacity Exceeded
                  </h3>
                  <p className="text-base text-muted-foreground mb-4">
                    You've assigned {capacityExceeded.requested} VIP{capacityExceeded.requested > 1 ? 's' : ''} to a vehicle with only {capacityExceeded.capacity} seat{capacityExceeded.capacity > 1 ? 's' : ''}.
                  </p>

                  <p className="text-base text-foreground font-medium mb-6">
                    Do you want to proceed anyway?
                  </p>

                  <div className="flex gap-3">
                    <button
                      onClick={handleCancelConflict}
                      className="flex-1 px-4 py-3 border border-input rounded-md text-base font-medium text-foreground hover:bg-accent"
                      style={{ minHeight: '44px' }}
                    >
                      Cancel
                    </button>
                    <button
                      onClick={handleForceSubmit}
                      disabled={isSubmitting}
                      className="flex-1 px-4 py-3 bg-orange-600 text-white rounded-md text-base font-medium hover:bg-orange-700 disabled:opacity-50"
                      style={{ minHeight: '44px' }}
                    >
                      {isSubmitting ? 'Saving...' : 'Save Anyway'}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}
    </>
  );
}
