import { useRef, useState, useEffect } from "react";
import { Button } from "@/components/ui/button";

interface Props {
  onCapture: (file: File) => void;
  buttonLabel?: string;
}

export function CameraCapture({ onCapture, buttonLabel = "Сделать фото" }: Props) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [preview, setPreview] = useState<string | null>(null);

  // Cleanup preview blob URL on unmount or when preview changes
  useEffect(() => {
    return () => {
      if (preview) URL.revokeObjectURL(preview);
    };
  }, [preview]);

  return (
    <div className="space-y-2">
      <input
        ref={inputRef}
        type="file"
        accept="image/*"
        capture="environment"
        className="hidden"
        aria-hidden="true"
        onChange={(e) => {
          const file = e.target.files?.[0];
          if (!file) return;
          if (preview) URL.revokeObjectURL(preview);
          setPreview(URL.createObjectURL(file));
          onCapture(file);
          // Reset input value so capturing the same file twice works
          e.target.value = "";
        }}
      />
      {preview ? (
        <div className="space-y-2">
          <img src={preview} alt="" className="w-full rounded-lg" />
          <Button
            variant="outline"
            className="w-full"
            onClick={() => inputRef.current?.click()}
          >
            Переснять
          </Button>
        </div>
      ) : (
        <Button onClick={() => inputRef.current?.click()} className="w-full">
          {buttonLabel}
        </Button>
      )}
    </div>
  );
}
