"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Car, Check } from "lucide-react";
import { DebouncedSearch } from "@/components/shared/debounced-search";
import { Skeleton } from "@/components/ui/skeleton";
import { useT } from "@/i18n";
import { cn } from "@/lib/cn";
import { friendlyErrorMessage } from "@/lib/errors";
import { queryKeys } from "@/lib/query-keys";
import { getVehicles } from "@/services/vehicles";
import type { Vehicle } from "@/types/vehicle";

/**
 * Choose a car that is already on the fleet's books.
 *
 * Only company cars with a plate are offered: a personal car belongs to its captain and cannot be handed on, and a row with no plate is a
 * captain's empty slot rather than a car. A car always has a captain on record, so the one chosen is usually somebody's: the list says whose, and
 * the dialog says what moving it means for them (they are left without a vehicle until another is assigned, and are not offered orders).
 */
export function ExistingVehiclePicker({
  selected,
  onSelect,
  captainUuid,
}: {
  selected: Vehicle | null;
  onSelect: (vehicle: Vehicle | null) => void;
  /** The captain being given the car: their own slot never appears as a car to choose. */
  captainUuid: string;
}) {
  const t = useT();
  const [search, setSearch] = useState("");

  const filters = { page: 1, rows: 8, search: search || undefined, ownership_type: "company_owned" as const, awaiting_assignment: false };
  const { data, isPending, isError, error } = useQuery({
    queryKey: queryKeys.vehicles.list({ ...filters, picker: true }),
    queryFn: () => getVehicles(filters),
  });

  const vehicles = (data?.Model ?? []).filter((vehicle) => vehicle.driver?.uuid !== captainUuid);

  return (
    <div className="grid gap-3">
      <DebouncedSearch value={search} onChange={setSearch} placeholder={t("vehicles.pickerSearch")} className="w-full" />

      <div className="max-h-64 space-y-2 overflow-y-auto" role="listbox" aria-label={t("vehicles.pickerTitle")}>
        {isPending ? (
          <>
            <Skeleton className="h-14 w-full" />
            <Skeleton className="h-14 w-full" />
          </>
        ) : isError ? (
          <p className="text-xs text-destructive">{friendlyErrorMessage(error, t)}</p>
        ) : vehicles.length === 0 ? (
          <p className="rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground">{t("vehicles.pickerEmpty")}</p>
        ) : (
          vehicles.map((vehicle) => {
            const isSelected = selected?.uuid === vehicle.uuid;

            return (
              <button
                key={vehicle.uuid}
                type="button"
                role="option"
                aria-selected={isSelected}
                onClick={() => onSelect(isSelected ? null : vehicle)}
                className={cn(
                  "flex w-full items-center gap-3 rounded-lg border p-3 text-start transition-colors",
                  isSelected ? "border-primary bg-primary/5" : "hover:bg-muted/60",
                )}
              >
                <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground" aria-hidden>
                  {isSelected ? <Check className="h-4 w-4 text-primary" /> : <Car className="h-4 w-4" />}
                </span>
                <span className="min-w-0 flex-1">
                  <span className="block truncate text-sm font-semibold text-foreground" dir="ltr" style={{ textAlign: "start" }}>
                    {vehicle.plate_number}
                  </span>
                  <span className="block truncate text-xs text-muted-foreground">
                    {[vehicle.brand, vehicle.model, vehicle.manufacture_year, vehicle.color].filter(Boolean).join(" · ")}
                  </span>
                </span>
                <span className="shrink-0 text-xs text-muted-foreground">
                  {vehicle.driver ? t("vehicles.pickerWith", { name: vehicle.driver.name }) : t("vehicles.pickerFree")}
                </span>
              </button>
            );
          })
        )}
      </div>

      {selected?.driver ? (
        <p className="rounded-lg border border-warning/40 bg-warning/5 p-3 text-xs leading-relaxed text-muted-foreground">
          {t("vehicles.pickerMoveNote", { plate: selected.plate_number ?? "", name: selected.driver.name })}
        </p>
      ) : null}
    </div>
  );
}
