import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { loadDamageVocabulary, damageTypeRuToEnum } from "@/data/damageVocabulary";

interface Props {
  open: boolean;
  zoneId: number;
  zoneLabel: string;
  pointsCount: number;
  onCancel: () => void;
  onSave: (data: { damageType: string; severity: 0 | 1 | 2 }) => void;
}

export function DamageClassifyDialog({ open, zoneId, zoneLabel, pointsCount, onCancel, onSave }: Props) {
  const [vocab, setVocab] = useState<Awaited<ReturnType<typeof loadDamageVocabulary>> | null>(null);
  const [damageType, setDamageType] = useState<string | null>(null);
  const [severity, setSeverity] = useState<0 | 1 | 2>(0);

  useEffect(() => {
    if (!open) return;
    setDamageType(null);
    setSeverity(0);
    loadDamageVocabulary().then(setVocab);
  }, [open]);

  if (!open) return null;

  // Salon zones (44=водительское сидение, 45=пассажирское, 46=задний диван) use salon_selectable; else exterior
  const isSalon = zoneId === 44 || zoneId === 45 || zoneId === 46;
  // Фильтруем типы для которых нет соответствия в backend DamageType enum —
  // иначе backend вернёт 422 на createMarker.
  const list = vocab
    ? (isSalon ? vocab.salon_selectable : vocab.exterior_selectable).filter(
        (dt) => damageTypeRuToEnum(dt) != null,
      )
    : [];

  return (
    <div
      className="fixed inset-0 z-50 bg-black/40 flex items-end sm:items-center justify-center p-0 sm:p-4"
      onClick={onCancel}
    >
      <div
        className="w-full max-w-md bg-card rounded-t-2xl sm:rounded-2xl shadow-xl flex flex-col max-h-[90vh]"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="p-5 border-b">
          <h2 className="text-lg font-semibold capitalize">{zoneLabel}</h2>
          <p className="text-xs text-muted-foreground">
            Точек: {pointsCount}
          </p>
        </header>

        <div className="p-5 border-b space-y-3">
          <Label>Степень повреждения</Label>
          <div className="flex items-center gap-2">
            {([0, 1, 2] as const).map((idx) => {
              const label = vocab?.severity_scale.labels[idx] ?? ["Лёгкое", "Среднее", "Тяжёлое"][idx];
              return (
                <button
                  key={idx}
                  type="button"
                  onClick={() => setSeverity(idx)}
                  className={cn(
                    "flex-1 py-2 px-2 rounded-md text-sm font-medium border transition-colors",
                    severity === idx
                      ? "bg-primary text-primary-foreground border-primary"
                      : "bg-background text-foreground hover:bg-accent"
                  )}
                >
                  {label}
                </button>
              );
            })}
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-5 space-y-1.5">
          <Label>Тип повреждения</Label>
          {!vocab && <div className="text-sm text-muted-foreground">Загружаю…</div>}
          {vocab && list.map((dt) => (
            <label
              key={dt}
              className={cn(
                "flex items-center gap-3 px-3 py-2.5 rounded-md cursor-pointer border transition-colors",
                damageType === dt
                  ? "bg-accent border-primary"
                  : "border-transparent hover:bg-accent/50"
              )}
            >
              <input
                type="radio"
                name="damage_type"
                value={dt}
                checked={damageType === dt}
                onChange={() => setDamageType(dt)}
                className="shrink-0"
              />
              <span className="text-sm">{dt}</span>
            </label>
          ))}
        </div>

        <footer className="p-5 border-t flex gap-2">
          <Button variant="outline" onClick={onCancel} className="flex-1">
            Отмена
          </Button>
          <Button
            disabled={!damageType}
            onClick={() => damageType && onSave({ damageType, severity })}
            className="flex-1"
          >
            Сохранить
          </Button>
        </footer>
      </div>
    </div>
  );
}
