"use client"

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

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

export function IdHoldingCapture({
  capturedImage,
  onCapture,
  onNext,
  onBack,
}: IdHoldingCaptureProps) {
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(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: 1280, height: 720 },
        audio: false,
      })
      if (videoRef.current) {
        videoRef.current.srcObject = stream
        setStreaming(true)
      }
    } catch {
      setError(
        "Camera access denied. Please enable camera permissions or use the upload option."
      )
    }
  }, [])

  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()
  }

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const reader = new FileReader()
    reader.onload = () => {
      const result = reader.result as string
      onCapture(result)
    }
    reader.readAsDataURL(file)
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div>
        <h2 className="text-xl font-semibold text-foreground">
          Photo Holding Your ID
        </h2>
        <p className="text-sm text-muted-foreground mt-1">
          Take a photo of yourself holding your government-issued ID next to your face.
          This confirms your identity matches the document.
        </p>
      </div>

      {/* Instruction Diagram */}
      <div className="rounded-xl border-2 border-primary/20 bg-primary/5 p-5">
        <div className="flex items-center gap-4">
          <div className="flex items-center justify-center size-14 rounded-full bg-primary/10 shrink-0">
            <UserCheck className="size-7 text-primary" />
          </div>
          <div className="flex flex-col gap-1">
            <h3 className="text-sm font-semibold text-foreground">
              How to take this photo
            </h3>
            <p className="text-sm text-muted-foreground leading-relaxed">
              Hold your ID card next to your face at chin level. Both your face and the
              front of your ID must be clearly visible and in focus.
            </p>
          </div>
        </div>
      </div>

      <div className="flex flex-col items-center gap-4">
        <div className="relative w-full max-w-lg 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="Photo of you holding your ID"
              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>
              <div className="flex gap-3">
                <Button variant="outline" size="sm" onClick={startCamera}>
                  Try Again
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => fileInputRef.current?.click()}
                  className="gap-1.5"
                >
                  <Upload className="size-3" />
                  Upload
                </Button>
              </div>
            </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>
              )}
              {/* Overlay guide: face + ID card outline */}
              <div className="absolute inset-0 pointer-events-none">
                {/* Face outline - upper portion */}
                <div className="absolute top-[8%] left-1/2 -translate-x-1/2">
                  <div className="size-32 md:size-40 rounded-full border-2 border-dashed border-primary/40" />
                </div>
                {/* ID card outline - lower left */}
                <div className="absolute bottom-[10%] left-[8%]">
                  <div className="w-36 h-24 md:w-44 md:h-28 rounded-lg border-2 border-dashed border-primary/40 flex items-center justify-center">
                    <span className="text-[10px] md:text-xs text-primary/40 font-medium uppercase tracking-wide">
                      ID Here
                    </span>
                  </div>
                </div>
                {/* Label */}
                <div className="absolute bottom-3 right-3 rounded-md bg-foreground/70 px-2.5 py-1">
                  <span className="text-[10px] md:text-xs font-medium text-background">
                    Hold ID next to face
                  </span>
                </div>
              </div>
            </>
          )}
        </div>
        <canvas ref={canvasRef} className="hidden" />
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          className="hidden"
          onChange={handleFileUpload}
          aria-label="Upload photo of yourself holding your ID"
        />

        {/* Capture Controls */}
        {!capturedImage && !error && (
          <div className="flex gap-3">
            <Button
              variant="outline"
              onClick={() => fileInputRef.current?.click()}
              className="gap-2"
            >
              <Upload className="size-4" />
              Upload Photo
            </Button>
            <Button
              onClick={takePhoto}
              disabled={!streaming}
              size="lg"
              className="gap-2 rounded-full px-8"
            >
              <Camera className="size-5" />
              Take Photo
            </Button>
          </div>
        )}

        {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-lg rounded-lg bg-secondary p-4">
          <h4 className="text-xs font-semibold text-secondary-foreground uppercase tracking-wider mb-2">
            Requirements for this 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" />
              Your face must be clearly visible and well-lit
            </li>
            <li className="flex items-start gap-2">
              <span className="size-1.5 rounded-full bg-primary mt-1.5 shrink-0" />
              Hold the front of your ID next to your chin
            </li>
            <li className="flex items-start gap-2">
              <span className="size-1.5 rounded-full bg-primary mt-1.5 shrink-0" />
              The name and photo on the ID must be readable
            </li>
            <li className="flex items-start gap-2">
              <span className="size-1.5 rounded-full bg-primary mt-1.5 shrink-0" />
              Do not cover any part of the ID with your fingers
            </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>
  )
}
