
import { Check } from "lucide-react";
import { User } from "@/types";
import { TripFormData } from "../schemas/tripFormSchema";
import { Control } from "react-hook-form";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator
} from "@/components/ui/command";

interface ExistingTravelerListProps {
  travelers: User[];
  searchTerm: string;
  setSearchTerm: (term: string) => void;
  control: Control<TripFormData>;
  handleSelectTraveler: (traveler: User) => void;
  onCreateNewClick: () => void;
  setOpen: (open: boolean) => void;
  formValue: "none" | "existing" | "new";
  selectedTravelerId?: string;
}

export function ExistingTravelerList({
  travelers,
  searchTerm,
  setSearchTerm,
  handleSelectTraveler,
  onCreateNewClick,
  setOpen,
  formValue,
  selectedTravelerId
}: ExistingTravelerListProps) {
  console.log("👥 Voyageurs disponibles:", travelers);
  console.log("🔍 Type de voyageur sélectionné:", formValue);
  console.log("✅ ID du voyageur sélectionné:", selectedTravelerId);

  const handleTravelerSelect = (traveler: User) => {
    console.log("Voyageur sélectionné:", traveler);

    // Appliquer la sélection immédiatement
    handleSelectTraveler(traveler);

    // Fermer le popover après un court délai pour éviter les problèmes d'état
    setTimeout(() => {
      setOpen(false);
    }, 100);
  };

  return (
    <Command>
      <CommandInput
        placeholder="Rechercher un voyageur..."
        value={searchTerm}
        onValueChange={setSearchTerm}
        autoFocus
      />
      <CommandList className="max-h-[300px] overflow-y-auto">
        <CommandEmpty>Aucun voyageur trouvé</CommandEmpty>
        <CommandGroup heading="Voyageurs existants">
          {travelers.length === 0 ? (
            <div className="px-2 py-3 text-sm text-muted-foreground">
              Aucun voyageur disponible. Créez-en un nouveau.
            </div>
          ) : (
            travelers.map((traveler) => (
              <CommandItem
                key={traveler.id || traveler.email}
                value={traveler.id || traveler.email}
                onSelect={() => handleTravelerSelect(traveler)}
                className="cursor-pointer flex items-center justify-between py-2"
              >
                <div>
                  <p className="font-medium">{traveler.name}</p>
                  <p className="text-sm text-muted-foreground">{traveler.email}</p>
                </div>
                <Check
                  className={`h-4 w-4 ml-2 ${
                    formValue === "existing" &&
                    (selectedTravelerId === traveler.id || (!traveler.id && selectedTravelerId === traveler.email))
                      ? "opacity-100"
                      : "opacity-0"
                  }`}
                />
              </CommandItem>
            ))
          )}
        </CommandGroup>
        <CommandSeparator />
        <CommandGroup>
          <CommandItem
            onSelect={() => {
              onCreateNewClick();
            }}
            className="cursor-pointer py-2"
          >
            <div className="flex items-center gap-2 text-primary">
              <UserPlusIcon className="h-4 w-4" />
              <span>Créer un nouveau voyageur</span>
            </div>
          </CommandItem>
        </CommandGroup>
      </CommandList>
    </Command>
  );
}

// Use a local component for the UserPlus icon to avoid circular imports
const UserPlusIcon = ({ className }: { className?: string }) => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="24"
    height="24"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
    className={className}
  >
    <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
    <circle cx="9" cy="7" r="4" />
    <line x1="19" x2="19" y1="8" y2="14" />
    <line x1="22" x2="16" y1="11" y2="11" />
  </svg>
);
