"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { BadgeCheck, CheckCircle2, Clock, Loader2, XCircle } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { BlueTick } from "@/components/ui/blue-tick"

type Status = "none" | "pending" | "approved" | "rejected"

/**
 * VerificationCard — lives at the bottom of the profile page.
 *
 * Four distinct states are rendered here:
 *   - verified:  show a confirmation with the blue tick.
 *   - pending:   show "Under review".
 *   - rejected:  show the admin's reason + allow a fresh re-apply.
 *   - none:      show the Apply-for-blue-tick form.
 *
 * On successful submit the card flips to the `pending` state
 * optimistically, and `router.refresh()` re-fetches the server data so
 * it stays in sync with the database.
 */
export function VerificationCard({
  verified,
  latestStatus,
  rejectionReason,
}: {
  verified: boolean
  latestStatus: Status
  rejectionReason: string | null
}) {
  const router = useRouter()

  // Pending is always derived from the database on first render; after
  // a successful submit we flip a local state immediately so the user
  // sees "under review" without waiting for the server roundtrip.
  const [localStatus, setLocalStatus] = useState<Status>(
    verified ? "approved" : latestStatus,
  )

  const [fullName, setFullName] = useState("")
  const [aadhaar, setAadhaar] = useState("")
  const [mobile, setMobile] = useState("")
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [showForm, setShowForm] = useState(false)

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setError(null)
    const digitsAadhaar = aadhaar.replace(/\D/g, "")
    const digitsMobile = mobile.replace(/\D/g, "")
    if (fullName.trim().length < 3) {
      return setError("Please enter your real full name")
    }
    if (digitsAadhaar.length !== 12) {
      return setError("Aadhaar must be exactly 12 digits")
    }
    if (digitsMobile.length < 10 || digitsMobile.length > 15) {
      return setError("Enter a valid mobile number")
    }
    setSubmitting(true)
    try {
      const res = await fetch("/api/verification", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          full_name: fullName.trim(),
          aadhaar: digitsAadhaar,
          mobile: digitsMobile,
        }),
      })
      if (!res.ok) {
        const data = (await res.json().catch(() => ({}))) as { error?: string }
        throw new Error(data.error || `Request failed (${res.status})`)
      }
      setLocalStatus("pending")
      setShowForm(false)
      setFullName("")
      setAadhaar("")
      setMobile("")
      router.refresh()
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not submit")
    } finally {
      setSubmitting(false)
    }
  }

  // --- State renderers ---------------------------------------------------

  if (verified || localStatus === "approved") {
    return (
      <Shell>
        <div className="flex items-center gap-3 rounded-xl bg-sky-50 p-4 text-sm dark:bg-sky-950/40">
          <BlueTick size={32} title="Verified" />
          <div>
            <p className="font-semibold text-sky-900 dark:text-sky-200">
              Your account is verified
            </p>
            <p className="text-xs text-sky-800/80 dark:text-sky-300/80">
              The blue tick is shown next to your name across the app.
            </p>
          </div>
        </div>
      </Shell>
    )
  }

  if (localStatus === "pending") {
    return (
      <Shell>
        <div className="flex items-center gap-3 rounded-xl bg-amber-50 p-4 text-sm dark:bg-amber-950/40">
          <Clock className="h-6 w-6 text-amber-600 dark:text-amber-300" aria-hidden="true" />
          <div>
            <p className="font-semibold text-amber-900 dark:text-amber-200">
              Application under review
            </p>
            <p className="text-xs text-amber-800/80 dark:text-amber-300/80">
              An admin will review your details and grant the blue tick if
              approved. You&apos;ll see the badge here once it&apos;s done.
            </p>
          </div>
        </div>
      </Shell>
    )
  }

  // Rejected or no prior request — both fall back to the apply form.
  return (
    <Shell>
      {localStatus === "rejected" && !showForm && (
        <div className="mb-4 flex items-start gap-3 rounded-xl bg-destructive/10 p-4 text-sm">
          <XCircle className="mt-0.5 h-5 w-5 shrink-0 text-destructive" aria-hidden="true" />
          <div>
            <p className="font-semibold text-destructive">
              Your previous application was rejected
            </p>
            {rejectionReason && (
              <p className="mt-1 text-xs text-destructive/90">
                Reason: {rejectionReason}
              </p>
            )}
            <p className="mt-1 text-xs text-muted-foreground">
              Double-check your details and try again below.
            </p>
          </div>
        </div>
      )}

      {!showForm ? (
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <p className="text-sm text-muted-foreground">
            Apply for the blue tick by submitting your real identity details.
            Admins review every application manually.
          </p>
          <Button
            type="button"
            onClick={() => setShowForm(true)}
            className="gap-1.5 self-start sm:self-auto"
          >
            <BadgeCheck className="h-4 w-4" aria-hidden="true" />
            Apply for blue tick
          </Button>
        </div>
      ) : (
        <form onSubmit={onSubmit} className="flex flex-col gap-4">
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="v-full-name">
              Real full name <span className="text-destructive">*</span>
            </Label>
            <Input
              id="v-full-name"
              required
              value={fullName}
              onChange={(e) => setFullName(e.target.value)}
              placeholder="As printed on your Aadhaar"
              autoComplete="name"
            />
          </div>
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div className="flex flex-col gap-1.5">
              <Label htmlFor="v-aadhaar">
                Aadhaar number <span className="text-destructive">*</span>
              </Label>
              <Input
                id="v-aadhaar"
                required
                inputMode="numeric"
                value={aadhaar}
                onChange={(e) => setAadhaar(e.target.value)}
                placeholder="12-digit Aadhaar"
                maxLength={14}
                autoComplete="off"
                className="font-mono"
              />
              <p className="text-[11px] text-muted-foreground">
                Stored securely and visible only to admins.
              </p>
            </div>
            <div className="flex flex-col gap-1.5">
              <Label htmlFor="v-mobile">
                Mobile number <span className="text-destructive">*</span>
              </Label>
              <Input
                id="v-mobile"
                required
                type="tel"
                inputMode="tel"
                value={mobile}
                onChange={(e) => setMobile(e.target.value)}
                placeholder="10-digit mobile"
                maxLength={15}
                autoComplete="tel"
                className="font-mono"
              />
            </div>
          </div>

          {error && (
            <p className="rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">
              {error}
            </p>
          )}

          <div className="flex items-center justify-end gap-2">
            <Button
              type="button"
              variant="ghost"
              onClick={() => {
                setShowForm(false)
                setError(null)
              }}
              disabled={submitting}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={submitting} className="min-w-36 gap-1.5">
              {submitting ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
                  Submitting…
                </>
              ) : (
                <>
                  <CheckCircle2 className="h-4 w-4" aria-hidden="true" />
                  Submit application
                </>
              )}
            </Button>
          </div>
        </form>
      )}
    </Shell>
  )
}

function Shell({ children }: { children: React.ReactNode }) {
  return (
    <section
      aria-label="Blue tick verification"
      className="overflow-hidden rounded-2xl border border-border bg-background p-6 shadow-sm md:p-8"
    >
      <header className="mb-4 flex items-center gap-3">
        <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-sky-100 text-sky-600 dark:bg-sky-950 dark:text-sky-300">
          <BadgeCheck className="h-4 w-4" aria-hidden="true" />
        </div>
        <div>
          <h2 className="text-sm font-semibold text-foreground">Blue tick verification</h2>
          <p className="text-xs text-muted-foreground">
            Get a verified badge on your profile and in video chat.
          </p>
        </div>
      </header>
      {children}
    </section>
  )
}
