"use client"

import { useRef, useState, useCallback, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Camera, RefreshCw, ArrowRight, ArrowLeft, User } from "lucide-react"
import { cn } from "@/lib/utils"

interface SelfieCaptureProps {
  capturedImage: string | null
  onCapture: (image: string) => void
  onNext: () => void
  onBack: () => void
}

export function SelfieCapture({
  capturedImage,
  onCapture,
  onNext,
  onBack,
}: SelfieCaptureProps) {
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [streaming, setStreaming] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const startCamera = useCallback(async () => {
    try {
      setError(null)
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: "user", width: 640, height: 480 },
        audio: false,
      })
      if (videoRef.current) {
        videoRef.current.srcObject = stream
        setStreaming(true)
      }
    } catch {
      setError(
        "Camera access denied. Please enable camera permissions in your browser settings."
      )
    }
  }, [])

  const stopCamera = useCallback(() => {
    if (videoRef.current?.srcObject) {
      const tracks = (videoRef.current.srcObject as MediaStream).getTracks()
      tracks.forEach((track) => track.stop())
      videoRef.current.srcObject = null
      setStreaming(false)
    }
  }, [])

  useEffect(() => {
    if (!capturedImage) {
      startCamera()
    }
    return () => {
      stopCamera()
    }
  }, [capturedImage, startCamera, stopCamera])

  const takePhoto = () => {
    if (!videoRef.current || !canvasRef.current) return
    const canvas = canvasRef.current
    const video = videoRef.current
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    const ctx = canvas.getContext("2d")
    if (ctx) {
      ctx.drawImage(video, 0, 0)
      const dataUrl = canvas.toDataURL("image/jpeg", 0.9)
      onCapture(dataUrl)
      stopCamera()
    }
  }

  const retake = () => {
    onCapture("")
    startCamera()
  }

  return (
    <div className="flex flex-col gap-6">
      <div>
        <h2 className="text-xl font-semibold text-foreground">Selfie Verification</h2>
        <p className="text-sm text-muted-foreground mt-1">
          Take a clear photo of your face. Make sure you are in a well-lit area and your
          face is fully visible.
        </p>
      </div>

      <div className="flex flex-col items-center gap-4">
        <div className="relative w-full max-w-md aspect-[4/3] rounded-xl overflow-hidden bg-muted border-2 border-border">
          {capturedImage ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={capturedImage}
              alt="Captured selfie"
              className="w-full h-full object-cover"
            />
          ) : error ? (
            <div className="flex flex-col items-center justify-center h-full gap-3 p-6 text-center">
              <div className="flex items-center justify-center size-16 rounded-full bg-destructive/10">
                <Camera className="size-8 text-destructive" />
              </div>
              <p className="text-sm text-destructive">{error}</p>
              <Button variant="outline" size="sm" onClick={startCamera}>
                Try Again
              </Button>
            </div>
          ) : (
            <>
              <video
                ref={videoRef}
                autoPlay
                playsInline
                muted
                className={cn(
                  "w-full h-full object-cover transition-opacity",
                  streaming ? "opacity-100" : "opacity-0"
                )}
              />
              {!streaming && (
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="flex flex-col items-center gap-2 text-muted-foreground">
                    <div className="animate-pulse">
                      <Camera className="size-10" />
                    </div>
                    <span className="text-sm">Starting camera...</span>
                  </div>
                </div>
              )}
              {/* Face outline overlay */}
              <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                <div className="size-48 md:size-56 rounded-full border-2 border-dashed border-primary/50 flex items-center justify-center">
                  <User className="size-16 text-primary/20" />
                </div>
              </div>
            </>
          )}
        </div>
        <canvas ref={canvasRef} className="hidden" />

        {/* Capture Controls */}
        {!capturedImage && !error && (
          <Button
            onClick={takePhoto}
            disabled={!streaming}
            size="lg"
            className="gap-2 rounded-full px-8"
          >
            <Camera className="size-5" />
            Take Photo
          </Button>
        )}

        {capturedImage && (
          <div className="flex gap-3">
            <Button variant="outline" onClick={retake} className="gap-2">
              <RefreshCw className="size-4" />
              Retake
            </Button>
          </div>
        )}

        {/* Tips */}
        <div className="w-full max-w-md rounded-lg bg-secondary p-4">
          <h4 className="text-xs font-semibold text-secondary-foreground uppercase tracking-wider mb-2">
            Tips for a good photo
          </h4>
          <ul className="flex flex-col gap-1.5 text-sm text-muted-foreground">
            <li className="flex items-start gap-2">
              <span className="size-1.5 rounded-full bg-primary mt-1.5 shrink-0" />
              Face the camera directly with a neutral expression
            </li>
            <li className="flex items-start gap-2">
              <span className="size-1.5 rounded-full bg-primary mt-1.5 shrink-0" />
              Ensure even lighting with no harsh shadows
            </li>
            <li className="flex items-start gap-2">
              <span className="size-1.5 rounded-full bg-primary mt-1.5 shrink-0" />
              Remove hats, sunglasses, and face coverings
            </li>
          </ul>
        </div>
      </div>

      <div className="flex justify-between pt-2">
        <Button variant="ghost" onClick={onBack} className="gap-2">
          <ArrowLeft className="size-4" />
          Back
        </Button>
        <Button onClick={onNext} disabled={!capturedImage} className="gap-2">
          Continue
          <ArrowRight className="size-4" />
        </Button>
      </div>
    </div>
  )
}
