import { useState } from 'react';
import { X } from 'lucide-react';

interface VIPFormProps {
  vip?: VIP | null;
  onSubmit: (data: VIPFormData) => void;
  onCancel: () => void;
  isSubmitting: boolean;
}

interface VIP {
  id: string;
  name: string;
  organization: string | null;
  department: string;
  arrivalMode: string;
  expectedArrival: string | null;
  airportPickup: boolean;
  venueTransport: boolean;
  notes: string | null;
}

export interface VIPFormData {
  name: string;
  organization?: string;
  department: string;
  arrivalMode: string;
  expectedArrival?: string;
  airportPickup?: boolean;
  venueTransport?: boolean;
  notes?: string;
}

export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps) {
  // Helper to convert ISO datetime to datetime-local format
  const toDatetimeLocal = (isoString: string | null) => {
    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<VIPFormData>({
    name: vip?.name || '',
    organization: vip?.organization || '',
    department: vip?.department || 'OFFICE_OF_DEVELOPMENT',
    arrivalMode: vip?.arrivalMode || 'FLIGHT',
    expectedArrival: toDatetimeLocal(vip?.expectedArrival || null),
    airportPickup: vip?.airportPickup ?? false,
    venueTransport: vip?.venueTransport ?? false,
    notes: vip?.notes || '',
  });

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

    // Clean up the data - remove empty strings for optional fields
    const cleanedData = {
      ...formData,
      organization: formData.organization || undefined,
      expectedArrival: formData.expectedArrival
        ? new Date(formData.expectedArrival).toISOString()
        : undefined,
      notes: formData.notes || undefined,
    };

    onSubmit(cleanedData);
  };

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

  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 w-full max-w-full md:max-w-2xl lg:max-w-3xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-4 md:p-6 border-b border-border">
          <h2 className="text-xl md:text-2xl font-bold text-foreground">
            {vip ? 'Edit VIP' : 'Add New VIP'}
          </h2>
          <button
            onClick={onCancel}
            className="text-muted-foreground hover:text-foreground p-2 rounded-md hover:bg-accent"
            style={{ minWidth: '44px', minHeight: '44px' }}
            aria-label="Close"
          >
            <X className="h-6 w-6" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-4 md:p-6 space-y-5">
          {/* Name */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              Full Name *
            </label>
            <input
              type="text"
              name="name"
              required
              value={formData.name}
              onChange={handleChange}
              className="w-full px-4 py-3 text-base bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              style={{ minHeight: '44px' }}
            />
          </div>

          {/* Organization */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              Organization
            </label>
            <input
              type="text"
              name="organization"
              value={formData.organization}
              onChange={handleChange}
              className="w-full px-4 py-3 text-base bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              style={{ minHeight: '44px' }}
            />
          </div>

          {/* Department */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              Department *
            </label>
            <select
              name="department"
              required
              value={formData.department}
              onChange={handleChange}
              className="w-full px-4 py-3 text-base bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              style={{ minHeight: '44px' }}
            >
              <option value="OFFICE_OF_DEVELOPMENT">Office of Development</option>
              <option value="ADMIN">Admin</option>
            </select>
          </div>

          {/* Arrival Mode */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              Arrival Mode *
            </label>
            <select
              name="arrivalMode"
              required
              value={formData.arrivalMode}
              onChange={handleChange}
              className="w-full px-4 py-3 text-base bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              style={{ minHeight: '44px' }}
            >
              <option value="FLIGHT">Flight</option>
              <option value="SELF_DRIVING">Self Driving</option>
            </select>
          </div>

          {/* Expected Arrival */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              Expected Arrival
            </label>
            <input
              type="datetime-local"
              name="expectedArrival"
              value={formData.expectedArrival}
              onChange={handleChange}
              className="w-full px-4 py-3 text-base bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              style={{ minHeight: '44px' }}
            />
          </div>

          {/* Transport Checkboxes */}
          <div className="space-y-3">
            <label className="flex items-center cursor-pointer" style={{ minHeight: '28px' }}>
              <input
                type="checkbox"
                name="airportPickup"
                checked={formData.airportPickup}
                onChange={handleChange}
                className="h-5 w-5 text-primary border-input rounded focus:ring-primary"
              />
              <span className="ml-3 text-base text-foreground">
                Airport pickup required
              </span>
            </label>

            <label className="flex items-center cursor-pointer" style={{ minHeight: '28px' }}>
              <input
                type="checkbox"
                name="venueTransport"
                checked={formData.venueTransport}
                onChange={handleChange}
                className="h-5 w-5 text-primary border-input rounded focus:ring-primary"
              />
              <span className="ml-3 text-base text-foreground">
                Venue transport required
              </span>
            </label>
          </div>

          {/* Notes */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              Notes
            </label>
            <textarea
              name="notes"
              value={formData.notes}
              onChange={handleChange}
              rows={3}
              placeholder="Any special requirements or notes"
              className="w-full px-4 py-3 text-base 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 flex-col sm:flex-row gap-3 pt-4">
            <button
              type="submit"
              disabled={isSubmitting}
              className="flex-1 bg-primary text-white py-3 px-4 rounded-md hover:bg-primary/90 disabled:opacity-50 font-medium"
              style={{ minHeight: '44px' }}
            >
              {isSubmitting ? 'Saving...' : vip ? 'Update VIP' : 'Create VIP'}
            </button>
            <button
              type="button"
              onClick={onCancel}
              className="flex-1 bg-muted text-foreground py-3 px-4 rounded-md hover:bg-muted/80 font-medium"
              style={{ minHeight: '44px' }}
            >
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
