"use client"

import { useRef, useState, useCallback, useEffect } from "react"
import { Button } from "@/components/ui/button"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Label } from "@/components/ui/label"
import {
  Camera,
  Upload,
  RefreshCw,
  ArrowRight,
  ArrowLeft,
  CreditCard,
} from "lucide-react"
import { cn } from "@/lib/utils"

interface IdCaptureProps {
  idType: string
  frontImage: string | null
  backImage: string | null
  onIdTypeChange: (type: string) => void
  onCaptureFront: (image: string) => void
  onCaptureBack: (image: string) => void
  onNext: () => void
  onBack: () => void
}

type CaptureMode = "front" | "back"

export function IdCapture({
  idType,
  frontImage,
  backImage,
  onIdTypeChange,
  onCaptureFront,
  onCaptureBack,
  onNext,
  onBack,
}: IdCaptureProps) {
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [streaming, setStreaming] = useState(false)
  const [cameraActive, setCameraActive] = useState(false)
  const [captureMode, setCaptureMode] = useState<CaptureMode>("front")
  const [error, setError] = useState<string | null>(null)

  const startCamera = useCallback(async () => {
    try {
      setError(null)
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: "environment", width: 1280, height: 720 },
        audio: false,
      })
      if (videoRef.current) {
        videoRef.current.srcObject = stream
        setStreaming(true)
        setCameraActive(true)
      }
    } catch {
      setError("Camera access denied. Please use the upload option instead.")
    }
  }, [])

  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)
      setCameraActive(false)
    }
  }, [])

  useEffect(() => {
    return () => {
      stopCamera()
    }
  }, [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)
      if (captureMode === "front") {
        onCaptureFront(dataUrl)
      } else {
        onCaptureBack(dataUrl)
      }
      stopCamera()
    }
  }

  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
      if (captureMode === "front") {
        onCaptureFront(result)
      } else {
        onCaptureBack(result)
      }
    }
    reader.readAsDataURL(file)
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  const retake = (side: CaptureMode) => {
    setCaptureMode(side)
    if (side === "front") {
      onCaptureFront("")
    } else {
      onCaptureBack("")
    }
  }

  const openCamera = (side: CaptureMode) => {
    setCaptureMode(side)
    startCamera()
  }

  const openUpload = (side: CaptureMode) => {
    setCaptureMode(side)
    fileInputRef.current?.click()
  }

  const currentImage = captureMode === "front" ? frontImage : backImage

  return (
    <div className="flex flex-col gap-6">
      <div>
        <h2 className="text-xl font-semibold text-foreground">
          Government ID Verification
        </h2>
        <p className="text-sm text-muted-foreground mt-1">
          Capture or upload clear images of the front and back of your
          government-issued photo ID.
        </p>
      </div>

      {/* ID Type Select */}
      <div className="flex flex-col gap-2">
        <Label htmlFor="idType">ID Document Type</Label>
        <Select value={idType} onValueChange={onIdTypeChange}>
          <SelectTrigger id="idType" className="w-full md:w-72">
            <SelectValue placeholder="Select ID type" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="drivers-license">{"Driver's License"}</SelectItem>
            <SelectItem value="state-id">State ID Card</SelectItem>
            <SelectItem value="passport">US Passport</SelectItem>
            <SelectItem value="passport-card">US Passport Card</SelectItem>
            <SelectItem value="military-id">Military ID</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Camera View */}
      {cameraActive && (
        <div className="flex flex-col items-center gap-4">
          <div className="relative w-full max-w-lg aspect-video rounded-xl overflow-hidden bg-muted border-2 border-primary/30">
            <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 animate-pulse">
                  <Camera className="size-10" />
                  <span className="text-sm">Starting camera...</span>
                </div>
              </div>
            )}
            {/* ID outline overlay */}
            <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
              <div className="w-[85%] h-[75%] rounded-lg border-2 border-dashed border-primary/40 flex items-center justify-center">
                <CreditCard className="size-12 text-primary/15" />
              </div>
            </div>
            {error && (
              <div className="absolute inset-0 bg-background/80 flex items-center justify-center p-6">
                <p className="text-sm text-destructive text-center">{error}</p>
              </div>
            )}
          </div>
          <div className="flex gap-3">
            <Button
              variant="outline"
              onClick={stopCamera}
            >
              Cancel
            </Button>
            <Button
              onClick={takePhoto}
              disabled={!streaming}
              className="gap-2"
            >
              <Camera className="size-4" />
              Capture {captureMode === "front" ? "Front" : "Back"}
            </Button>
          </div>
        </div>
      )}

      <canvas ref={canvasRef} className="hidden" />
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        capture="environment"
        className="hidden"
        onChange={handleFileUpload}
        aria-label="Upload ID document image"
      />

      {/* ID Cards Grid */}
      {!cameraActive && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Front of ID */}
          <div className="flex flex-col gap-3">
            <Label className="text-sm font-medium">Front of ID</Label>
            {frontImage ? (
              <div className="relative aspect-video rounded-xl overflow-hidden border-2 border-accent bg-muted">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={frontImage}
                  alt="Front of ID document"
                  className="w-full h-full object-cover"
                />
                <div className="absolute top-2 right-2">
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() => retake("front")}
                    className="gap-1.5 text-xs"
                  >
                    <RefreshCw className="size-3" />
                    Retake
                  </Button>
                </div>
                <div className="absolute bottom-2 left-2 rounded-md bg-accent px-2 py-1 text-xs font-medium text-accent-foreground">
                  Captured
                </div>
              </div>
            ) : (
              <div className="aspect-video rounded-xl border-2 border-dashed border-border bg-secondary flex flex-col items-center justify-center gap-3">
                <CreditCard className="size-10 text-muted-foreground" />
                <p className="text-sm text-muted-foreground">Front of your ID</p>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => openCamera("front")}
                    className="gap-1.5 text-xs"
                  >
                    <Camera className="size-3" />
                    Camera
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => openUpload("front")}
                    className="gap-1.5 text-xs"
                  >
                    <Upload className="size-3" />
                    Upload
                  </Button>
                </div>
              </div>
            )}
          </div>

          {/* Back of ID */}
          <div className="flex flex-col gap-3">
            <Label className="text-sm font-medium">Back of ID</Label>
            {backImage ? (
              <div className="relative aspect-video rounded-xl overflow-hidden border-2 border-accent bg-muted">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={backImage}
                  alt="Back of ID document"
                  className="w-full h-full object-cover"
                />
                <div className="absolute top-2 right-2">
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() => retake("back")}
                    className="gap-1.5 text-xs"
                  >
                    <RefreshCw className="size-3" />
                    Retake
                  </Button>
                </div>
                <div className="absolute bottom-2 left-2 rounded-md bg-accent px-2 py-1 text-xs font-medium text-accent-foreground">
                  Captured
                </div>
              </div>
            ) : (
              <div className="aspect-video rounded-xl border-2 border-dashed border-border bg-secondary flex flex-col items-center justify-center gap-3">
                <CreditCard className="size-10 text-muted-foreground" />
                <p className="text-sm text-muted-foreground">Back of your ID</p>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => openCamera("back")}
                    className="gap-1.5 text-xs"
                  >
                    <Camera className="size-3" />
                    Camera
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => openUpload("back")}
                    className="gap-1.5 text-xs"
                  >
                    <Upload className="size-3" />
                    Upload
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Supported Documents */}
      <div className="rounded-lg bg-secondary p-4">
        <h4 className="text-xs font-semibold text-secondary-foreground uppercase tracking-wider mb-2">
          Accepted Documents
        </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" />
            {"State-issued driver's license or ID card"}
          </li>
          <li className="flex items-start gap-2">
            <span className="size-1.5 rounded-full bg-primary mt-1.5 shrink-0" />
            US Passport or Passport Card
          </li>
          <li className="flex items-start gap-2">
            <span className="size-1.5 rounded-full bg-primary mt-1.5 shrink-0" />
            Military identification card
          </li>
        </ul>
      </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={!idType || !frontImage}
          className="gap-2"
        >
          Continue
          <ArrowRight className="size-4" />
        </Button>
      </div>
    </div>
  )
}
