/**
 * Экран выбора машины перед созданием ремонта (Фича 3).
 *
 * Открывается из `/repairs` по кнопке «+ Добавить ремонт».
 * Поиск по госномеру (У44 — релевантность). После тапа на строку
 * переходим в `/repairs/new/:carId` (CreateRepairPage).
 */
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ChevronLeft, Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { searchCars, type CarBrief } from "@/api/repairsCreate";

export default function CarSelectPage() {
  const navigate = useNavigate();
  const [q, setQ] = useState("");
  const [cars, setCars] = useState<CarBrief[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [extOpen, setExtOpen] = useState(false);
  const [extPlate, setExtPlate] = useState("");
  const [extMake, setExtMake] = useState("");

  const continueExternal = () => {
    const plate = extPlate.trim();
    if (!plate) return;
    navigate("/repairs/new-external", { state: { plate, make: extMake.trim() || null } });
  };

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    const t = setTimeout(async () => {
      try {
        const list = await searchCars(q);
        if (!cancelled) setCars(list);
      } catch (e) {
        if (!cancelled) setError((e as Error).message || "Не удалось загрузить машины");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }, 200); // debounce
    return () => {
      cancelled = true;
      clearTimeout(t);
    };
  }, [q]);

  return (
    <div className="min-h-screen bg-background flex flex-col">
      <header className="sticky top-0 z-10 bg-background/95 backdrop-blur border-b">
        <div className="flex items-center gap-2 p-3">
          <Button variant="ghost" size="sm" onClick={() => navigate("/repairs")} className="-ml-2">
            <ChevronLeft className="h-5 w-5" />
          </Button>
          <h1 className="text-base font-semibold">Выберите машину</h1>
        </div>
        <div className="px-3 pb-3">
          <div className="relative">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              autoFocus
              placeholder="Госномер…"
              value={q}
              onChange={(e) => setQ(e.target.value)}
              className="pl-8"
            />
          </div>
        </div>
      </header>
      <main className="flex-1 container max-w-2xl py-3">
        <button
          type="button"
          onClick={() => setExtOpen(true)}
          className="w-full mb-3 flex items-center justify-center gap-1 rounded-md border border-dashed bg-card hover:bg-accent/40 transition-colors p-3 text-sm font-medium text-muted-foreground"
        >
          + Машина не из парка
        </button>
        {error && (
          <div className="rounded-md border border-destructive bg-destructive/10 p-3 text-sm">
            {error}
          </div>
        )}
        {loading ? (
          <div className="space-y-2">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="h-12 rounded-md bg-muted animate-pulse" />
            ))}
          </div>
        ) : cars.length === 0 ? (
          <div className="text-center text-sm text-muted-foreground py-12">
            {q ? "Ничего не найдено" : "Нет активных машин в парке"}
          </div>
        ) : (
          <ul className="space-y-1">
            {cars.map((c) => (
              <li key={c.id}>
                <button
                  type="button"
                  onClick={() => navigate(`/repairs/new/${c.id}`)}
                  className="w-full flex items-baseline justify-between gap-3 rounded-md border bg-card hover:bg-accent/40 transition-colors p-3 text-left"
                >
                  <span className="font-medium">{c.plate}</span>
                  <span className="text-sm text-muted-foreground truncate">
                    {[c.brand, c.model].filter(Boolean).join(" ")}
                  </span>
                </button>
              </li>
            ))}
          </ul>
        )}
      </main>
      {extOpen && (
        <div className="fixed inset-0 z-50 bg-background/95 flex flex-col">
          <header className="border-b p-3 flex items-center gap-2">
            <Button variant="ghost" size="sm" onClick={() => setExtOpen(false)}>
              Отмена
            </Button>
            <h2 className="text-base font-semibold">Машина с улицы</h2>
          </header>
          <main className="flex-1 container max-w-2xl py-4 space-y-4">
            <div>
              <label className="text-sm font-medium">Госномер *</label>
              <Input
                autoFocus
                value={extPlate}
                onChange={(e) => setExtPlate(e.target.value)}
                placeholder="Х999ХХ199"
                className="mt-1"
                onKeyDown={(e) => e.key === "Enter" && continueExternal()}
              />
            </div>
            <div>
              <label className="text-sm font-medium">Марка и модель (необязательно)</label>
              <Input
                value={extMake}
                onChange={(e) => setExtMake(e.target.value)}
                placeholder="Toyota Camry"
                className="mt-1"
              />
            </div>
            <Button className="w-full" disabled={!extPlate.trim()} onClick={continueExternal}>
              Продолжить →
            </Button>
          </main>
        </div>
      )}
    </div>
  );
}
