import { useState } from "react";
import { CameraCapture } from "./CameraCapture";
import { AuthImg } from "@/components/AuthImg";
import { uploadPhoto } from "@/api/photos";
import { toast } from "sonner";

interface Props {
  inspectionId: number;
  side: string;
  slotIndex: number;
  label: string;
  initialPhotoId?: number;
  onUploaded?: (photoId: number) => void;
}

export function PhotoSlot({
  inspectionId,
  side,
  slotIndex,
  label,
  initialPhotoId,
  onUploaded,
}: Props) {
  const [photoId, setPhotoId] = useState<number | undefined>(initialPhotoId);
  const [uploading, setUploading] = useState(false);

  async function handleCapture(file: File) {
    setUploading(true);
    try {
      const result = await uploadPhoto(inspectionId, side, slotIndex, file);
      setPhotoId(result.id);
      onUploaded?.(result.id);
      toast.success(`${label}: загружено`);
    } catch {
      toast.error(`${label}: ошибка загрузки`);
    } finally {
      setUploading(false);
    }
  }

  return (
    <div className="border rounded-lg p-3 bg-card space-y-2">
      <div className="text-sm font-medium">{label}</div>
      {photoId && (
        <AuthImg
          src={`photos/${photoId}/thumb`}
          alt={label}
          className="w-full aspect-[4/3] object-cover rounded bg-muted"
        />
      )}
      <CameraCapture
        onCapture={handleCapture}
        buttonLabel={photoId ? "Заменить" : "Снять"}
      />
      {uploading && (
        <div className="text-xs text-muted-foreground">Загружаю…</div>
      )}
    </div>
  );
}
