import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Camera, RefreshCw, CheckCircle2 } from "lucide-react";
import { captureFaceDescriptor, type FaceDescriptor } from "@/lib/face";
import { toast } from "sonner";

interface Props {
  onCapture: (descriptor: FaceDescriptor) => void;
  buttonLabel?: string;
}

export function FaceCapture({ onCapture, buttonLabel = "Capture Face" }: Props) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [streaming, setStreaming] = useState(false);
  const [captured, setCaptured] = useState(false);

  const start = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: "user", width: 480, height: 480 },
      });
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        await videoRef.current.play();
        setStreaming(true);
      }
    } catch {
      toast.error("Camera access denied. Please grant camera permissions.");
    }
  };

  const stop = () => {
    const v = videoRef.current;
    if (v?.srcObject) {
      (v.srcObject as MediaStream).getTracks().forEach((t) => t.stop());
      v.srcObject = null;
    }
    setStreaming(false);
  };

  useEffect(() => () => stop(), []);

  const handleCapture = async () => {
    if (!videoRef.current) return;
    try {
      const desc = await captureFaceDescriptor(videoRef.current);
      setCaptured(true);
      onCapture(desc);
      stop();
      toast.success("Face captured successfully");
    } catch {
      toast.error("Capture failed");
    }
  };

  return (
    <div className="space-y-3">
      <div className="relative aspect-square w-full max-w-xs mx-auto rounded-xl overflow-hidden bg-muted border-2 border-primary/20">
        <video ref={videoRef} className="w-full h-full object-cover" muted playsInline />
        {!streaming && !captured && (
          <div className="absolute inset-0 flex items-center justify-center text-muted-foreground">
            <Camera className="h-12 w-12 opacity-40" />
          </div>
        )}
        {captured && (
          <div className="absolute inset-0 flex flex-col items-center justify-center bg-success/20 backdrop-blur-sm">
            <CheckCircle2 className="h-16 w-16 text-success" />
            <p className="mt-2 text-sm font-medium">Captured</p>
          </div>
        )}
      </div>
      <div className="flex gap-2 justify-center">
        {!streaming && !captured && (
          <Button type="button" onClick={start} variant="default">
            <Camera className="h-4 w-4 mr-2" /> Start Camera
          </Button>
        )}
        {streaming && (
          <Button type="button" onClick={handleCapture}>
            <Camera className="h-4 w-4 mr-2" /> {buttonLabel}
          </Button>
        )}
        {captured && (
          <Button type="button" variant="outline" onClick={() => { setCaptured(false); start(); }}>
            <RefreshCw className="h-4 w-4 mr-2" /> Retake
          </Button>
        )}
      </div>
    </div>
  );
}
