import { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { ChevronDown, AlertTriangle, X } from 'lucide-react';
import { formatDateTime } from '@/lib/utils';

interface Driver {
  id: string;
  name: string;
  phone?: string;
}

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

interface InlineDriverSelectorProps {
  eventId: string;
  currentDriverId?: string | null;
  currentDriverName?: string | null;
  onDriverChange?: () => void;
}

export function InlineDriverSelector({
  eventId,
  currentDriverId,
  currentDriverName,
  onDriverChange,
}: InlineDriverSelectorProps) {
  const queryClient = useQueryClient();
  const [isOpen, setIsOpen] = useState(false);
  const [showConflictDialog, setShowConflictDialog] = useState(false);
  const [conflicts, setConflicts] = useState<ScheduleConflict[]>([]);
  const [pendingDriverId, setPendingDriverId] = useState<string | null>(null);

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

  // Update driver mutation
  const updateDriverMutation = useMutation({
    mutationFn: async ({ driverId, forceAssign = false }: { driverId: string | null; forceAssign?: boolean }) => {
      await api.patch(`/events/${eventId}`, {
        driverId,
        forceAssign,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['events'] });
      setIsOpen(false);
      setShowConflictDialog(false);
      setPendingDriverId(null);
      setConflicts([]);
      toast.success('Driver assigned successfully');
      onDriverChange?.();
    },
    onError: (error: any) => {
      console.error('[DRIVER] Assignment failed:', error);

      // Check if this is a conflict error
      if (error.response?.data?.conflicts) {
        setConflicts(error.response.data.conflicts);
        setShowConflictDialog(true);
        setIsOpen(false);
      } else {
        toast.error(error.response?.data?.message || 'Failed to assign driver');
        setIsOpen(false);
      }
    },
  });

  // Handle driver selection
  const handleSelectDriver = (driverId: string | null) => {
    setPendingDriverId(driverId);
    updateDriverMutation.mutate({ driverId });
  };

  // Handle force assign (override conflict)
  const handleForceAssign = () => {
    if (pendingDriverId !== null) {
      updateDriverMutation.mutate({
        driverId: pendingDriverId,
        forceAssign: true,
      });
    }
  };

  // Handle cancel conflict dialog
  const handleCancelConflict = () => {
    setShowConflictDialog(false);
    setPendingDriverId(null);
    setConflicts([]);
  };

  const selectedDriver = drivers?.find(d => d.id === currentDriverId);
  const displayName = selectedDriver?.name || currentDriverName || 'Unassigned';

  return (
    <>
      <button
        onClick={() => setIsOpen(true)}
        className={`inline-flex items-center gap-1 px-2 py-1 text-sm rounded transition-colors ${
          currentDriverId
            ? 'text-foreground hover:bg-accent'
            : 'text-muted-foreground hover:bg-muted'
        }`}
        disabled={updateDriverMutation.isPending}
      >
        <span>{displayName}</span>
        <ChevronDown className="h-3 w-3" />
      </button>

      {/* Driver Selection Modal */}
      {isOpen && createPortal(
        <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 w-full max-w-md max-h-[80vh] overflow-hidden">
            <div className="flex items-center justify-between p-4 border-b border-border sticky top-0 bg-card">
              <h2 className="text-lg font-semibold text-foreground">Assign Driver</h2>
              <button
                onClick={() => setIsOpen(false)}
                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-5 w-5" />
              </button>
            </div>

            <div className="overflow-y-auto max-h-[calc(80vh-8rem)]">
              {driversLoading ? (
                <div className="p-8 text-center text-muted-foreground">Loading drivers...</div>
              ) : (
                <div className="p-2">
                  <button
                    onClick={() => handleSelectDriver(null)}
                    className="w-full text-left px-4 py-3 text-base text-muted-foreground hover:bg-muted transition-colors rounded-md"
                    style={{ minHeight: '44px' }}
                  >
                    Unassigned
                  </button>
                  {drivers?.map((driver) => (
                    <button
                      key={driver.id}
                      onClick={() => handleSelectDriver(driver.id)}
                      className={`w-full text-left px-4 py-3 text-base transition-colors rounded-md ${
                        driver.id === currentDriverId
                          ? 'bg-blue-50 text-blue-700 font-medium'
                          : 'text-foreground hover:bg-muted'
                      }`}
                      style={{ minHeight: '44px' }}
                    >
                      <div>{driver.name}</div>
                      {driver.phone && (
                        <div className="text-sm text-muted-foreground">{driver.phone}</div>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* Conflict Dialog */}
      {showConflictDialog && createPortal(
        <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 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-foreground">{conflict.title}</div>
                        <div className="text-sm text-muted-foreground 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={handleForceAssign}
                      disabled={updateDriverMutation.isPending}
                      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' }}
                    >
                      {updateDriverMutation.isPending ? 'Assigning...' : 'Assign Anyway'}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}
    </>
  );
}
