"use client";

import { useEffect } from "react";
import { useCamera, type CameraStatus } from "@/hooks/use-camera";

interface CameraCaptureProps {
  onCapture: (photo: Blob) => void;
  disabled?: boolean;
}

export function CameraCapture({ onCapture, disabled }: CameraCaptureProps) {
  const { videoRef, status, start, capture } = useCamera();

  useEffect(() => {
    start();
  }, [start]);

  const handleCapture = async () => {
    try {
      const blob = await capture();
      onCapture(blob);
    } catch {
      // Capture failures are rare (video not ready yet); the button is
      // disabled until status === "ready", so just let the user retry.
    }
  };

  return (
    <div className="flex flex-col items-center gap-3">
      <div className="relative aspect-[3/4] w-full max-w-sm overflow-hidden rounded-xl bg-black">
        <video ref={videoRef} autoPlay playsInline muted className="h-full w-full object-cover" />
        {status !== "ready" && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/70 px-4 text-center text-sm text-white">
            {statusMessage(status)}
          </div>
        )}
      </div>

      {status === "denied" && (
        <button type="button" onClick={start} className="text-sm text-blue-600 underline">
          Coba izinkan kamera lagi
        </button>
      )}

      <button
        type="button"
        onClick={handleCapture}
        disabled={disabled || status !== "ready"}
        className="w-full max-w-sm rounded-full bg-blue-600 px-6 py-3 font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
      >
        Ambil Foto
      </button>
    </div>
  );
}

function statusMessage(status: CameraStatus): string {
  switch (status) {
    case "starting":
      return "Membuka kamera...";
    case "denied":
      return "Izin kamera ditolak. Aktifkan akses kamera di pengaturan browser.";
    case "unavailable":
      return "Kamera tidak tersedia di perangkat ini.";
    default:
      return "Menyiapkan kamera...";
  }
}
