import { useState } from "react";
import { useParams, useNavigate, useSearchParams } from "react-router-dom";
import { useQuery, useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import { getVehicle, getTtHistory } from "@/api/vehicles";
import { createInspection, type InspectionType } from "@/api/inspections";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const INSPECTION_TYPE_LABELS: Record<InspectionType, string> = {
  handover: "Выдача",
  return: "Приёмка",
  periodic: "Плановый",
  "ad-hoc": "Свободный",
  initial: "Первичный",
  seizure: "Изъятие",
  "equipment-change": "Комплектация",
  "pre-repair": "В ремонт",
  "post-repair": "Из ремонта",
};

const STATUS_LABELS: Record<string, string> = {
  in_progress: "В работе",
  completed: "Завершён",
  cancelled: "Отменён",
};

function timeAgo(iso: string): string {
  const sec = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
  if (sec < 60) return "только что";
  const min = Math.floor(sec / 60);
  if (min < 60) return `${min} мин назад`;
  const h = Math.floor(min / 60);
  if (h < 24) return `${h} ч назад`;
  const d = Math.floor(h / 24);
  if (d < 30) return `${d} дн назад`;
  return new Date(iso).toLocaleDateString("ru-RU");
}

export default function VehicleCard() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const vehicleId = Number(id);

  const action = searchParams.get("action") || undefined;

  const [pendingType, setPendingType] = useState<InspectionType | null>(null);
  const [mileageInput, setMileageInput] = useState("");
  const [mileageSource, setMileageSource] = useState<
    "starline" | "last-inspection" | null
  >(null);

  const { data: v, isLoading, isError } = useQuery({
    queryKey: ["vehicle", vehicleId],
    queryFn: () => getVehicle(vehicleId),
  });

  // История из vendor (Element Mechanic). Молча возвращает пустой список
  // если машина ещё не синхронизирована — секцию просто скрываем.
  const { data: tt } = useQuery({
    queryKey: ["vehicle", vehicleId, "tt-history"],
    queryFn: () => getTtHistory(vehicleId),
    enabled: Number.isFinite(vehicleId),
    staleTime: 5 * 60_000,
  });

  const startInspection = useMutation({
    mutationFn: (input: { type: InspectionType; mileage: number | undefined }) =>
      createInspection({ vehicle_id: vehicleId, type: input.type, mileage: input.mileage }),
    onSuccess: (inspection) => {
      navigate(`/inspections/${inspection.id}/edit`);
    },
    onError: () => toast.error("Не удалось создать осмотр"),
  });

  const handleStartClick = (type: InspectionType) => {
    setPendingType(type);
    // Приоритет: 1) StarLine OBD (свежий одометр), 2) пробег прошлого
    // осмотра. Менеджер всегда может скорректировать.
    if (v?.starline_mileage != null) {
      setMileageInput(String(v.starline_mileage));
      setMileageSource("starline");
      return;
    }
    const lastWithMileage = v?.recent_inspections.find((i) => i.mileage != null);
    if (lastWithMileage?.mileage != null) {
      setMileageInput(String(lastWithMileage.mileage));
      setMileageSource("last-inspection");
      return;
    }
    setMileageInput("");
    setMileageSource(null);
  };

  if (isLoading)
    return <div className="p-8 text-muted-foreground">Загружаю…</div>;
  if (isError || !v)
    return <div className="p-8 text-destructive">Машина не найдена.</div>;

  return (
    <div className="min-h-screen bg-background p-4 space-y-4">
      <button
        onClick={() => navigate(`/vehicles${action ? `?action=${action}` : ""}`)}
        className="text-sm text-muted-foreground hover:text-foreground"
      >
        ← К списку
      </button>

      <Card className="p-4">
        <div className="flex items-center gap-2 flex-wrap">
          <div className="text-xl font-semibold">{v.license_plate}</div>
          {v.status && (
            <span
              className={`inline-flex items-center text-xs font-medium px-2 py-0.5 rounded-full ${
                {
                  "На линии": "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",
                  "Простой": "bg-muted text-muted-foreground",
                  "Ремонтируется": "bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",
                  "Ждет ремонта": "bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",
                  "ДТП": "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300",
                  "Бронь": "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
                  "Выкуп": "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
                  "На продаже": "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
                  "Подготовка на продажу": "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
                  "Ждет доставки до офиса": "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
                }[v.status] ?? "bg-muted text-muted-foreground"
              }`}
            >
              {v.status}
            </span>
          )}
        </div>
        <div className="text-sm text-muted-foreground">
          {[v.make, v.model, v.year].filter(Boolean).join(" ") || "—"}
        </div>
        {v.vin && (
          <div className="text-xs text-muted-foreground mt-1">VIN: {v.vin}</div>
        )}
      </Card>

      <div>
        <h2 className="text-sm font-semibold text-muted-foreground mb-2">
          Начать осмотр
        </h2>
        <div className="grid grid-cols-2 gap-2">
          <Button
            onClick={() => handleStartClick("handover")}
            disabled={startInspection.isPending}
          >
            Выдача
          </Button>
          <Button
            onClick={() => handleStartClick("return")}
            disabled={startInspection.isPending}
          >
            Приёмка
          </Button>
          <Button
            variant="outline"
            onClick={() => handleStartClick("periodic")}
            disabled={startInspection.isPending}
            className="col-span-2"
          >
            Плановый
          </Button>
        </div>
      </div>

      <div>
        <h2 className="text-sm font-semibold text-muted-foreground mb-2">
          Прошлые осмотры
        </h2>
        {v.recent_inspections.length === 0 ? (
          <Card className="p-4 text-sm text-muted-foreground">
            Осмотров ещё не было.
          </Card>
        ) : (
          <div className="space-y-2">
            {v.recent_inspections.map((i) => (
              <Card
                key={i.id}
                className="p-3 cursor-pointer hover:shadow-md transition-shadow"
                onClick={() => navigate(`/inspections/${i.id}`)}
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <div className="font-medium">
                        {INSPECTION_TYPE_LABELS[i.type as InspectionType] ?? i.type}
                      </div>
                      {(i.photos_count ?? 0) > 0 && (
                        <span
                          className="inline-flex items-center gap-1 text-xs text-muted-foreground"
                          title={`Фото: ${i.photos_count}`}
                        >
                          📷 {i.photos_count}
                        </span>
                      )}
                    </div>
                    <div className="text-xs text-muted-foreground mt-1 flex items-center gap-2 flex-wrap">
                      <span>{new Date(i.started_at).toLocaleString("ru-RU")}</span>
                      {i.mileage != null && (
                        <>
                          <span className="text-muted-foreground/50">·</span>
                          <span>{i.mileage.toLocaleString("ru-RU")} км</span>
                        </>
                      )}
                    </div>
                    {i.driver_name && (
                      <div className="text-xs mt-1 text-foreground/80 truncate">
                        👤 {i.driver_name}
                      </div>
                    )}
                  </div>
                  <div className="text-xs text-muted-foreground shrink-0">
                    {STATUS_LABELS[i.status] ?? i.status}
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>

      {tt && tt.states.length > 0 && (
        <div>
          <h2 className="text-sm font-semibold text-muted-foreground mb-2">
            История осмотров (Element Mechanic)
          </h2>
          <div className="space-y-2">
            {tt.states.map((s) => {
              const date = s.unix_time
                ? new Date(s.unix_time * 1000).toLocaleString("ru-RU")
                : "—";
              return (
                <Card
                  key={s.id}
                  className="p-3 cursor-pointer hover:shadow-md transition-shadow"
                  onClick={() => navigate(`/tt-states/${s.id}`)}
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex-1 min-w-0">
                      <div className="font-medium">
                        {s.mechanic_name || "Осмотр"}
                      </div>
                      <div className="text-xs text-muted-foreground mt-1 flex items-center gap-2 flex-wrap">
                        <span>{date}</span>
                        {s.mileage != null && (
                          <>
                            <span className="text-muted-foreground/50">·</span>
                            <span>{s.mileage.toLocaleString("ru-RU")} км</span>
                          </>
                        )}
                      </div>
                      {s.driver_name && (
                        <div className="text-xs mt-1 text-foreground/80 truncate">
                          👤 {s.driver_name}
                        </div>
                      )}
                    </div>
                    <div className="text-xs text-muted-foreground shrink-0 text-right">
                      <div>📷 {s.photos_count}</div>
                      {s.damages_count > 0 && (
                        <div className="text-destructive mt-0.5">
                          ⚠ {s.damages_count}
                        </div>
                      )}
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
        </div>
      )}

      {pendingType && (
        <div
          className="fixed inset-0 z-50 bg-black/40 flex items-end sm:items-center justify-center p-0 sm:p-4"
          onClick={() => setPendingType(null)}
        >
          <div
            className="w-full max-w-sm bg-card rounded-t-2xl sm:rounded-2xl shadow-xl p-5 space-y-4"
            onClick={(e) => e.stopPropagation()}
          >
            <div>
              <h2 className="text-lg font-semibold">
                {INSPECTION_TYPE_LABELS[pendingType]}
              </h2>
              <p className="text-xs text-muted-foreground mt-1">
                Введите пробег машины на текущий момент.
              </p>
            </div>

            <div className="space-y-1">
              <Label htmlFor="mileage">Пробег, км</Label>
              <Input
                id="mileage"
                type="text"
                inputMode="numeric"
                pattern="[0-9]*"
                value={mileageInput}
                onChange={(e) => {
                  setMileageInput(e.target.value.replace(/\D/g, ""));
                  setMileageSource(null);
                }}
                placeholder="123456"
                autoFocus
              />
              {mileageSource === "starline" && (
                <div className="text-[11px] text-muted-foreground flex items-center gap-1.5">
                  <span className="inline-block w-1.5 h-1.5 rounded-full bg-emerald-500" />
                  <span>
                    Из StarLine
                    {v?.starline_mileage_at && (
                      <> · {timeAgo(v.starline_mileage_at)}</>
                    )}
                  </span>
                  <span className="text-muted-foreground/60">
                    · скорректируйте если надо
                  </span>
                </div>
              )}
              {mileageSource === "last-inspection" && (
                <div className="text-[11px] text-muted-foreground">
                  Из прошлого осмотра · скорректируйте если надо
                </div>
              )}
            </div>

            <div className="flex gap-2">
              <Button
                variant="outline"
                onClick={() => setPendingType(null)}
                className="flex-1"
              >
                Отмена
              </Button>
              <Button
                disabled={startInspection.isPending}
                onClick={() => {
                  const m = mileageInput.trim() ? Number(mileageInput) : undefined;
                  startInspection.mutate({
                    type: pendingType,
                    mileage: m && Number.isFinite(m) ? m : undefined,
                  });
                }}
                className="flex-1"
              >
                {startInspection.isPending ? "Создаём…" : "Начать"}
              </Button>
            </div>

            <button
              type="button"
              onClick={() => {
                startInspection.mutate({ type: pendingType, mileage: undefined });
              }}
              className="w-full text-xs text-muted-foreground hover:text-foreground"
            >
              Пропустить пробег
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
