import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import { CameraCapture } from "@/components/camera/CameraCapture";
import { AuthImg } from "@/components/AuthImg";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { uploadPhoto } from "@/api/photos";
import { createMarker, type MarkerSummary } from "@/api/inspections";

const WEAR_LEVELS: { value: string; label: string; description: string }[] = [
  {
    value: "cosmetic",
    label: "Новая",
    description: "Протектор полный, без признаков износа",
  },
  {
    value: "minor",
    label: "Норма",
    description: "Естественный износ, эксплуатация в норме",
  },
  {
    value: "moderate",
    label: "Износ",
    description: "Заметный износ, требует наблюдения",
  },
  {
    value: "severe",
    label: "Менять",
    description: "Критический износ, замена необходима",
  },
];

interface Props {
  open: boolean;
  inspectionId: number;
  onClose: () => void;
  onCreated: (marker: MarkerSummary) => void;
}

export function TireWearDialog({
  open,
  inspectionId,
  onClose,
  onCreated,
}: Props) {
  const [level, setLevel] = useState<string>("minor");
  const [description, setDescription] = useState("");
  const [photoId, setPhotoId] = useState<number | undefined>(undefined);
  const [uploading, setUploading] = useState(false);

  async function handlePhoto(file: File) {
    setUploading(true);
    try {
      const result = await uploadPhoto(inspectionId, "free", 0, file);
      setPhotoId(result.id);
      toast.success("Фото загружено");
    } catch {
      toast.error("Ошибка загрузки фото");
    } finally {
      setUploading(false);
    }
  }

  const createMut = useMutation({
    mutationFn: () =>
      createMarker(inspectionId, {
        side: "tires",
        severity: level,
        // "not-working" is the closest existing damage_type enum value.
        // The semantically meaningful field here is `severity` (wear level).
        damage_type: "not-working",
        description:
          description.trim() ||
          `Состояние резины: ${WEAR_LEVELS.find((w) => w.value === level)?.label ?? level}`,
        photo_id: photoId,
        x: null,
        y: null,
      }),
    onSuccess: (marker) => {
      onCreated(marker);
      reset();
    },
    onError: () => toast.error("Не удалось сохранить"),
  });

  function reset() {
    setLevel("minor");
    setDescription("");
    setPhotoId(undefined);
  }

  function handleClose() {
    reset();
    onClose();
  }

  if (!open) return 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={handleClose}
    >
      <div
        className="w-full max-w-md bg-card rounded-t-2xl sm:rounded-2xl shadow-xl p-5 space-y-4 max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold">Состояние резины</h2>
          <button
            type="button"
            onClick={handleClose}
            className="text-muted-foreground hover:text-foreground text-2xl leading-none"
            aria-label="Закрыть"
          >
            ×
          </button>
        </div>

        {/* Wear level — radio cards for large touch targets */}
        <div className="space-y-2">
          <Label>Уровень износа</Label>
          <div className="space-y-2">
            {WEAR_LEVELS.map((w) => (
              <label
                key={w.value}
                className={
                  "flex items-start gap-3 rounded-lg border p-3 cursor-pointer transition-colors " +
                  (level === w.value
                    ? "border-primary bg-accent"
                    : "border-input hover:bg-accent/50")
                }
              >
                <input
                  type="radio"
                  name="tire_wear"
                  value={w.value}
                  checked={level === w.value}
                  onChange={() => setLevel(w.value)}
                  className="mt-0.5 shrink-0"
                />
                <div>
                  <div className="font-medium text-sm">{w.label}</div>
                  <div className="text-xs text-muted-foreground">
                    {w.description}
                  </div>
                </div>
              </label>
            ))}
          </div>
        </div>

        {/* Optional comment */}
        <div className="space-y-2">
          <Label htmlFor="tire_comment">Комментарий (опционально)</Label>
          <Input
            id="tire_comment"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Например: глубина протектора ~3 мм"
          />
        </div>

        {/* Optional photo */}
        <div className="space-y-2">
          <Label>Фото (опционально)</Label>
          {photoId ? (
            <div className="space-y-2">
              <AuthImg
                src={`photos/${photoId}/thumb`}
                alt="Фото резины"
                className="w-full aspect-[4/3] object-cover rounded bg-muted"
              />
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => setPhotoId(undefined)}
                className="w-full"
              >
                Удалить фото
              </Button>
            </div>
          ) : (
            <CameraCapture
              onCapture={handlePhoto}
              buttonLabel={uploading ? "Загружаю…" : "Сделать фото"}
            />
          )}
        </div>

        {/* Actions */}
        <div className="flex gap-2 pt-2">
          <Button
            type="button"
            variant="outline"
            onClick={handleClose}
            className="flex-1"
          >
            Отмена
          </Button>
          <Button
            type="button"
            disabled={createMut.isPending || uploading}
            onClick={() => createMut.mutate()}
            className="flex-1"
          >
            {createMut.isPending ? "Сохраняю…" : "Сохранить"}
          </Button>
        </div>
      </div>
    </div>
  );
}
