import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useQuery } from '@tanstack/react-query';
import { X, AlertTriangle, Users, Car } from 'lucide-react';
import { api } from '@/lib/api';
import { ScheduleEvent, VIP, Driver, Vehicle } from '@/types';
import { formatDateTime } from '@/lib/utils';

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;
  forceAssign?: boolean;
}

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

export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraActions }: EventFormProps) {
  // 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 [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 || '',
  });

  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: ['vips'],
    queryFn: async () => {
      const { data } = await api.get('/vips');
      return data;
    },
  });

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

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

  // Get selected vehicle capacity
  const selectedVehicle = vehicles?.find(v => v.id === formData.vehicleId);
  const seatsUsed = formData.vipIds.length;
  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,
    };

    // 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 = vips
    ?.filter(vip => formData.vipIds.includes(vip.id))
    .map(vip => vip.name)
    .join(', ') || 'None selected';

  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">
            {/* 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.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 used
                  {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"
                >
                  <option value="TRANSPORT">Transport</option>
                  <option value="MEETING">Meeting</option>
                  <option value="EVENT">Event</option>
                  <option value="MEAL">Meal</option>
                  <option value="ACCOMMODATION">Accommodation</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"
                >
                  <option value="SCHEDULED">Scheduled</option>
                  <option value="IN_PROGRESS">In Progress</option>
                  <option value="COMPLETED">Completed</option>
                  <option value="CANCELLED">Cancelled</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
      )}
    </>
  );
}
