"use client"

import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import {
  ArrowLeft,
  ShieldCheck,
  FileText,
  User,
  CreditCard,
  Camera,
  UserCheck,
} from "lucide-react"
import { useState } from "react"

interface ConsentReviewProps {
  personalInfo: {
    firstName: string
    lastName: string
    email: string
    phone: string
    dateOfBirth: string
    ssn: string
    address: string
    city: string
    state: string
    zip: string
  }
  selfieImage: string | null
  idFrontImage: string | null
  idBackImage: string | null
  holdingIdImage: string | null
  idType: string
  onBack: () => void
  onSubmit: () => void
}

export function ConsentReview({
  personalInfo,
  selfieImage,
  idFrontImage,
  idBackImage,
  holdingIdImage,
  idType,
  onBack,
  onSubmit,
}: ConsentReviewProps) {
  const [consentBackground, setConsentBackground] = useState(false)
  const [consentTerms, setConsentTerms] = useState(false)
  const [consentAccuracy, setConsentAccuracy] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [submitError, setSubmitError] = useState<string | null>(null)
  const [refNumber] = useState(() => `CV-${Date.now().toString(36).toUpperCase()}`)

  const canSubmit = consentBackground && consentTerms && consentAccuracy && !isSubmitting

  const handleSubmit = async () => {
    setIsSubmitting(true)
    setSubmitError(null)

    try {
      const response = await fetch("/api/submit-verification", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          personalInfo,
          selfieImage,
          idFrontImage,
          idBackImage,
          holdingIdImage,
          idType,
          referenceNumber: refNumber,
        }),
      })

      if (!response.ok) {
        throw new Error("Submission failed")
      }

      setSubmitted(true)
      onSubmit()
    } catch {
      setSubmitError("There was a problem submitting your verification. Please try again.")
    } finally {
      setIsSubmitting(false)
    }
  }

  if (submitted) {
    return (
      <div className="flex flex-col items-center gap-6 py-8 text-center">
        <div className="flex items-center justify-center size-20 rounded-full bg-accent/10">
          <ShieldCheck className="size-10 text-accent" />
        </div>
        <div>
          <h2 className="text-2xl font-semibold text-foreground">
            Verification Submitted
          </h2>
          <p className="text-muted-foreground mt-2 max-w-md mx-auto leading-relaxed">
            Your identity verification has been submitted successfully. You will receive
            an email at{" "}
            <span className="font-medium text-foreground">
              {personalInfo.email}
            </span>{" "}
            with your background check results within 2-3 business days.
          </p>
        </div>
        <div className="rounded-lg border border-border bg-card p-4 w-full max-w-sm">
          <p className="text-xs text-muted-foreground uppercase tracking-wider font-semibold mb-2">
            Reference Number
          </p>
          <p className="text-lg font-mono font-bold text-foreground">
            {refNumber}
          </p>
        </div>
      </div>
    )
  }

  const idTypeLabels: Record<string, string> = {
    "drivers-license": "Driver's License",
    "state-id": "State ID Card",
    passport: "US Passport",
    "passport-card": "US Passport Card",
    "military-id": "Military ID",
  }

  return (
    <div className="flex flex-col gap-6">
      <div>
        <h2 className="text-xl font-semibold text-foreground">
          Review & Consent
        </h2>
        <p className="text-sm text-muted-foreground mt-1">
          Review your information and provide consent to proceed with the
          background check.
        </p>
      </div>

      {/* Summary Cards */}
      <div className="flex flex-col gap-3">
        <div className="rounded-lg border border-border bg-card p-4">
          <div className="flex items-start gap-3">
            <div className="flex items-center justify-center size-9 rounded-lg bg-primary/10 shrink-0">
              <FileText className="size-4 text-primary" />
            </div>
            <div className="flex-1 min-w-0">
              <h4 className="text-sm font-semibold text-foreground">
                Personal Information
              </h4>
              <div className="mt-1.5 grid grid-cols-2 gap-x-4 gap-y-1 text-sm">
                <div>
                  <span className="text-muted-foreground">Name: </span>
                  <span className="text-foreground font-medium">
                    {personalInfo.firstName} {personalInfo.lastName}
                  </span>
                </div>
                <div>
                  <span className="text-muted-foreground">Email: </span>
                  <span className="text-foreground font-medium">
                    {personalInfo.email}
                  </span>
                </div>
                <div>
                  <span className="text-muted-foreground">DOB: </span>
                  <span className="text-foreground font-medium">
                    {personalInfo.dateOfBirth}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <div className="rounded-lg border border-border bg-card p-4">
            <div className="flex items-start gap-3">
              <div className="flex items-center justify-center size-9 rounded-lg bg-primary/10 shrink-0">
                <Camera className="size-4 text-primary" />
              </div>
              <div className="flex-1 min-w-0">
                <h4 className="text-sm font-semibold text-foreground">
                  Selfie Photo
                </h4>
                {selfieImage ? (
                  <div className="mt-2 size-16 rounded-lg overflow-hidden border border-border">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={selfieImage}
                      alt="Your selfie"
                      className="w-full h-full object-cover"
                    />
                  </div>
                ) : (
                  <div className="mt-2 flex items-center gap-1.5">
                    <User className="size-4 text-muted-foreground" />
                    <span className="text-sm text-muted-foreground">
                      Not captured
                    </span>
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="rounded-lg border border-border bg-card p-4">
            <div className="flex items-start gap-3">
              <div className="flex items-center justify-center size-9 rounded-lg bg-primary/10 shrink-0">
                <CreditCard className="size-4 text-primary" />
              </div>
              <div className="flex-1 min-w-0">
                <h4 className="text-sm font-semibold text-foreground">
                  Government ID
                </h4>
                <p className="text-sm text-muted-foreground mt-0.5">
                  {idTypeLabels[idType] || "Not selected"}
                </p>
                {idFrontImage && (
                  <div className="mt-2 w-20 h-12 rounded-md overflow-hidden border border-border">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={idFrontImage}
                      alt="Front of ID"
                      className="w-full h-full object-cover"
                    />
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="rounded-lg border border-border bg-card p-4">
            <div className="flex items-start gap-3">
              <div className="flex items-center justify-center size-9 rounded-lg bg-primary/10 shrink-0">
                <UserCheck className="size-4 text-primary" />
              </div>
              <div className="flex-1 min-w-0">
                <h4 className="text-sm font-semibold text-foreground">
                  Holding ID Photo
                </h4>
                {holdingIdImage ? (
                  <div className="mt-2 size-16 rounded-lg overflow-hidden border border-border">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={holdingIdImage}
                      alt="You holding your ID"
                      className="w-full h-full object-cover"
                    />
                  </div>
                ) : (
                  <div className="mt-2 flex items-center gap-1.5">
                    <UserCheck className="size-4 text-muted-foreground" />
                    <span className="text-sm text-muted-foreground">
                      Not captured
                    </span>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Consent Checkboxes */}
      <div className="flex flex-col gap-4 rounded-lg border border-border bg-card p-5">
        <h3 className="text-sm font-semibold text-foreground">
          Authorization & Consent
        </h3>
        <div className="flex items-start gap-3">
          <Checkbox
            id="consent-bg"
            checked={consentBackground}
            onCheckedChange={(v) => setConsentBackground(v === true)}
          />
          <Label htmlFor="consent-bg" className="text-sm leading-relaxed text-foreground cursor-pointer">
            I authorize ClearVerify to conduct a background investigation including
            criminal records, employment history, and education verification.
          </Label>
        </div>
        <div className="flex items-start gap-3">
          <Checkbox
            id="consent-terms"
            checked={consentTerms}
            onCheckedChange={(v) => setConsentTerms(v === true)}
          />
          <Label htmlFor="consent-terms" className="text-sm leading-relaxed text-foreground cursor-pointer">
            I have read and agree to the Terms of Service and Privacy Policy. I
            understand my personal data will be processed in accordance with
            applicable laws.
          </Label>
        </div>
        <div className="flex items-start gap-3">
          <Checkbox
            id="consent-accuracy"
            checked={consentAccuracy}
            onCheckedChange={(v) => setConsentAccuracy(v === true)}
          />
          <Label htmlFor="consent-accuracy" className="text-sm leading-relaxed text-foreground cursor-pointer">
            I certify that the information provided is accurate and complete to
            the best of my knowledge. I understand that providing false
            information may disqualify me.
          </Label>
        </div>
      </div>

      {submitError && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
          {submitError}
        </div>
      )}

      <div className="flex justify-between pt-2">
        <Button variant="ghost" onClick={onBack} disabled={isSubmitting} className="gap-2">
          <ArrowLeft className="size-4" />
          Back
        </Button>
        <Button
          onClick={handleSubmit}
          disabled={!canSubmit}
          className="gap-2"
        >
          {isSubmitting ? (
            <>
              <svg className="size-4 animate-spin" viewBox="0 0 24 24" fill="none">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              Submitting...
            </>
          ) : (
            <>
              <ShieldCheck className="size-4" />
              Submit Verification
            </>
          )}
        </Button>
      </div>
    </div>
  )
}
