"use client"

import { useMemo, useState, useTransition } from "react"
import Link from "next/link"
import { useRouter, useSearchParams } from "next/navigation"
import {
  BadgeCheck,
  CheckCircle2,
  Loader2,
  Phone,
  XCircle,
  IdCard,
  UserRound,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { BlueTick } from "@/components/ui/blue-tick"
import { cn } from "@/lib/utils"

export type VerificationRequestItem = {
  id: string
  userId: string
  fullName: string
  aadhaar: string
  mobile: string
  status: "pending" | "approved" | "rejected"
  rejectionReason: string | null
  createdAt: string
  reviewedAt: string | null
  displayName: string | null
  avatarUrl: string | null
  verified: boolean
  email: string | null
}

type TabStatus = "pending" | "approved" | "rejected"

const TAB_LABEL: Record<TabStatus, string> = {
  pending: "Pending",
  approved: "Approved",
  rejected: "Rejected",
}

export function VerificationQueue({
  items,
  status,
}: {
  items: VerificationRequestItem[]
  status: TabStatus
}) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [busyId, setBusyId] = useState<string | null>(null)
  const [, startTransition] = useTransition()
  const [actionError, setActionError] = useState<string | null>(null)

  const tabs: TabStatus[] = useMemo(() => ["pending", "approved", "rejected"], [])

  const setTab = (next: TabStatus) => {
    const p = new URLSearchParams(searchParams?.toString())
    if (next === "pending") p.delete("status")
    else p.set("status", next)
    router.push(`/admin/verification${p.toString() ? `?${p.toString()}` : ""}`)
  }

  const act = async (id: string, action: "approve" | "reject") => {
    setActionError(null)
    let reason: string | null = null
    if (action === "reject") {
      const input = window.prompt(
        "Reason for rejection (optional, shown to the user):",
      )
      reason = input ?? null
    } else {
      const confirmed = window.confirm(
        "Approve this request and grant the blue tick?",
      )
      if (!confirmed) return
    }
    setBusyId(id)
    try {
      const res = await fetch(`/api/admin/verification/${id}`, {
        method: "PATCH",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ action, reason }),
      })
      if (!res.ok) {
        const data = (await res.json().catch(() => ({}))) as { error?: string }
        throw new Error(data.error || `Request failed (${res.status})`)
      }
      // Re-fetch the current tab so the row disappears / moves tabs.
      startTransition(() => router.refresh())
    } catch (err) {
      setActionError(err instanceof Error ? err.message : "Action failed")
    } finally {
      setBusyId(null)
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-col items-stretch justify-between gap-3 sm:flex-row sm:items-center">
        <div className="flex items-center gap-2">
          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
            <BadgeCheck className="h-4 w-4" aria-hidden="true" />
          </div>
          <div>
            <h2 className="text-sm font-semibold text-foreground">Blue tick requests</h2>
            <p className="text-xs text-muted-foreground">
              Review verification applications from users.
            </p>
          </div>
        </div>
        <div className="inline-flex rounded-lg border border-border bg-background p-1">
          {tabs.map((t) => {
            const active = t === status
            return (
              <button
                key={t}
                type="button"
                onClick={() => setTab(t)}
                className={cn(
                  "rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
                  active
                    ? "bg-primary text-primary-foreground shadow-sm"
                    : "text-muted-foreground hover:bg-muted hover:text-foreground",
                )}
                aria-pressed={active}
              >
                {TAB_LABEL[t]}
              </button>
            )
          })}
        </div>
      </div>

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

      {items.length === 0 ? (
        <div className="flex flex-col items-center justify-center gap-2 rounded-xl border border-border bg-background px-6 py-12 text-center shadow-sm">
          <BadgeCheck className="h-8 w-8 text-muted-foreground" aria-hidden="true" />
          <p className="text-sm font-medium text-foreground">
            No {TAB_LABEL[status].toLowerCase()} requests
          </p>
          <p className="text-xs text-muted-foreground">
            {status === "pending"
              ? "Pending applications will appear here."
              : status === "approved"
                ? "Approved users show up here after you grant a tick."
                : "Rejected applications are kept here for reference."}
          </p>
        </div>
      ) : (
        <ul className="grid grid-cols-1 gap-3 lg:grid-cols-2">
          {items.map((r) => {
            const initial = (r.displayName || r.email || "?")
              .trim()
              .charAt(0)
              .toUpperCase()
            const isBusy = busyId === r.id
            return (
              <li
                key={r.id}
                className="flex flex-col gap-4 rounded-2xl border border-border bg-background p-4 shadow-sm"
              >
                <header className="flex items-start justify-between gap-3">
                  <Link
                    href={`/admin/users/${r.userId}`}
                    className="flex min-w-0 items-center gap-3 hover:opacity-90"
                  >
                    {r.avatarUrl ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={r.avatarUrl || "/placeholder.svg"}
                        alt=""
                        className="h-11 w-11 shrink-0 rounded-full object-cover"
                      />
                    ) : (
                      <span
                        aria-hidden="true"
                        className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-primary text-sm font-semibold text-primary-foreground"
                      >
                        {initial}
                      </span>
                    )}
                    <div className="min-w-0">
                      <p className="flex items-center gap-1 truncate text-sm font-semibold text-foreground">
                        <span className="truncate">
                          {r.displayName || r.email || "Unknown user"}
                        </span>
                        {r.verified && <BlueTick size={14} title="Verified" />}
                      </p>
                      <p className="truncate text-xs text-muted-foreground">
                        {r.email ?? r.userId}
                      </p>
                    </div>
                  </Link>
                  <StatusPill status={r.status} />
                </header>

                <dl className="grid grid-cols-1 gap-2 rounded-lg bg-muted/40 p-3 text-xs sm:grid-cols-2">
                  <Field
                    icon={<UserRound className="h-3.5 w-3.5" />}
                    label="Full name"
                    value={r.fullName}
                  />
                  <Field
                    icon={<Phone className="h-3.5 w-3.5" />}
                    label="Mobile"
                    value={r.mobile}
                    mono
                  />
                  <Field
                    icon={<IdCard className="h-3.5 w-3.5" />}
                    label="Aadhaar"
                    value={formatAadhaar(r.aadhaar)}
                    mono
                    className="sm:col-span-2"
                  />
                </dl>

                <div className="flex flex-wrap items-center justify-between gap-2">
                  <p className="text-[11px] text-muted-foreground">
                    Submitted {formatDate(r.createdAt)}
                    {r.reviewedAt && ` · Reviewed ${formatDate(r.reviewedAt)}`}
                  </p>
                  {r.status === "pending" ? (
                    <div className="flex flex-wrap gap-2">
                      <Button
                        type="button"
                        size="sm"
                        variant="outline"
                        disabled={isBusy}
                        onClick={() => act(r.id, "reject")}
                        className="h-8 gap-1.5 border-destructive/30 text-destructive hover:bg-destructive/10 hover:text-destructive"
                      >
                        {isBusy ? (
                          <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
                        ) : (
                          <XCircle className="h-3.5 w-3.5" aria-hidden="true" />
                        )}
                        Reject
                      </Button>
                      <Button
                        type="button"
                        size="sm"
                        disabled={isBusy}
                        onClick={() => act(r.id, "approve")}
                        className="h-8 gap-1.5"
                      >
                        {isBusy ? (
                          <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
                        ) : (
                          <CheckCircle2 className="h-3.5 w-3.5" aria-hidden="true" />
                        )}
                        Approve
                      </Button>
                    </div>
                  ) : r.status === "rejected" && r.rejectionReason ? (
                    <p className="max-w-full truncate rounded-md bg-destructive/10 px-2 py-1 text-[11px] text-destructive">
                      Reason: {r.rejectionReason}
                    </p>
                  ) : null}
                </div>
              </li>
            )
          })}
        </ul>
      )}
    </div>
  )
}

function StatusPill({ status }: { status: "pending" | "approved" | "rejected" }) {
  const styles =
    status === "approved"
      ? "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300"
      : status === "rejected"
        ? "border-destructive/30 bg-destructive/10 text-destructive"
        : "border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300"
  return (
    <span
      className={cn(
        "inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] font-medium",
        styles,
      )}
    >
      {status === "approved"
        ? "Approved"
        : status === "rejected"
          ? "Rejected"
          : "Pending"}
    </span>
  )
}

function Field({
  icon,
  label,
  value,
  mono,
  className,
}: {
  icon: React.ReactNode
  label: string
  value: string
  mono?: boolean
  className?: string
}) {
  return (
    <div className={cn("flex flex-col gap-0.5", className)}>
      <dt className="flex items-center gap-1 text-[10px] uppercase tracking-wide text-muted-foreground">
        {icon}
        {label}
      </dt>
      <dd
        className={cn(
          "break-words text-foreground",
          mono ? "font-mono text-[13px]" : "text-sm",
        )}
      >
        {value}
      </dd>
    </div>
  )
}

// Aadhaar numbers are 12 digits — display grouped for readability
// (xxxx xxxx xxxx). We show it to admins raw because they need to
// verify the ID, but grouping keeps the UI legible.
function formatAadhaar(raw: string) {
  const digits = raw.replace(/\D/g, "")
  if (digits.length !== 12) return raw
  return `${digits.slice(0, 4)} ${digits.slice(4, 8)} ${digits.slice(8, 12)}`
}

function formatDate(iso: string) {
  try {
    const d = new Date(iso)
    return d.toLocaleString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    })
  } catch {
    return iso
  }
}
