'use client'

import { useEffect, useMemo, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useTranslation } from "react-i18next"
import {
  AlertTriangle,
  ArrowUpLeft,
  CheckCircle2,
  Clock,
  Download,
  Eye,
  ExternalLink,
  FileCheck,
  FileText,
  Maximize2,
  Minimize2,
  Search,
  ShieldAlert,
  UserRound,
  XCircle,
} from "lucide-react"

import { AvatarBadge } from "@/components/ui/avatar-badge"
import { Button } from "@/components/ui/button"
import { DataTable, type Column } from "@/components/ui/data-table"
import { KpiCard } from "@/components/ui/kpi-card"
import { Modal } from "@/components/ui/modal"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { ENDPOINTS } from "@/constants/endpoints"
import { useKyc } from "@/hooks/useKyc"
import { api } from "@/lib/api"
import { formatDateTime } from "@/lib/format"
import type { KycApplicationDTO } from "@/types"

type KycDocument = {
  id: string
  document_type: string
  document_number: string | null
  status: string
  expiry_date: string | null
  rejection_reason: string | null
  file_name: string | null
  mime_type: string | null
}

type AmlScreening = { id: string; status: string; screening_type: string; provider: string | null; screened_at: string }
type RiskProfile = { risk_level: string; risk_score: string | number; reasons: Record<string, unknown> | null }

const copy = {
  en: {
    title: "Identity verification and compliance (KYC)", description: "Review the customer profile, identity evidence, AML results, and risk before making a decision.",
    customers: "Customers", queue: "KYC review queue", pending: "Pending review", approved: "Approved", rejected: "Rejected", highRisk: "High risk",
    search: "Search by customer, code, email, phone, or application ID", allStatuses: "All statuses", application: "Application", customer: "Customer",
    level: "KYC level", risk: "Risk", status: "Status", submitted: "Submitted", noCases: "No KYC applications match these filters.",
    review: "Review case", selectCase: "Select an application to begin the review.", openCustomer: "Open customer profile", linkedCustomer: "Linked customer",
    workflow: "Review path", stepCustomer: "Customer profile", stepIdentity: "Identity and documents", stepCompliance: "AML and risk", stepDecision: "Decision",
    readiness: "Review readiness", identityPresent: "Identity details present", identityValid: "Identity document not expired", customerLinked: "Customer profile linked",
    documentsPresent: "Supporting documents attached", noDocuments: "No supporting documents are attached. Open the customer profile to complete the file.",
    identity: "Identity", identityType: "Identity type", identityNumber: "Identity number", identityExpiry: "Identity expiry", contact: "Customer contact",
    email: "Email", phone: "Phone", customerCode: "Customer code", documents: "Documents", compliance: "AML and risk",
    noAml: "No AML screening result is available.", riskProfile: "Risk profile", score: "Score", decision: "Decision", rejectionReason: "Reason for rejection",
    rejectionPlaceholder: "State the exact reason and what the customer must correct...", approve: "Approve KYC", reject: "Reject KYC", approvalHelp: "Approval verifies identity and activates the linked customer.",
    rejectedReason: "Rejection reason", completed: "This review is complete.", nextCustomer: "Next: return to the customer profile to continue customer operations.",
    requiredReason: "Enter a rejection reason before rejecting the application.", actionFailed: "The KYC decision could not be saved.", loading: "Loading review data...",
    submittedStatus: "Submitted", reviewStatus: "Under review", approvedStatus: "Approved", rejectedStatus: "Rejected", expiredStatus: "Expired", pendingStatus: "Pending",
    low: "Low", medium: "Medium", high: "High", critical: "Critical", basic: "Basic", intermediate: "Intermediate", premium: "Premium", missing: "Missing", ready: "Ready",
  },
  ar: {
    title: "التحقق من الهوية والامتثال (KYC)", description: "راجع ملف العميل والهوية والمستندات ونتائج مكافحة غسل الأموال والمخاطر قبل اتخاذ القرار.",
    customers: "العملاء", queue: "قائمة مراجعة التحقق", pending: "قيد المراجعة", approved: "تمت الموافقة", rejected: "مرفوضة", highRisk: "مخاطر عالية",
    search: "ابحث باسم العميل أو الكود أو البريد أو الهاتف أو رقم الطلب", allStatuses: "كل الحالات", application: "رقم الطلب", customer: "العميل",
    level: "مستوى التحقق", risk: "المخاطر", status: "الحالة", submitted: "تاريخ التقديم", noCases: "لا توجد طلبات تحقق مطابقة.",
    review: "مراجعة الطلب", selectCase: "اختر طلباً لبدء المراجعة.", openCustomer: "فتح ملف العميل", linkedCustomer: "ملف العميل المرتبط",
    workflow: "مسار المراجعة", stepCustomer: "ملف العميل", stepIdentity: "الهوية والمستندات", stepCompliance: "الامتثال والمخاطر", stepDecision: "القرار",
    readiness: "جاهزية المراجعة", identityPresent: "بيانات الهوية مكتملة", identityValid: "وثيقة الهوية غير منتهية", customerLinked: "ملف العميل مرتبط",
    documentsPresent: "المستندات الداعمة مرفقة", noDocuments: "لا توجد مستندات داعمة. افتح ملف العميل لاستكمال البيانات.",
    identity: "بيانات الهوية", identityType: "نوع الهوية", identityNumber: "رقم الهوية", identityExpiry: "انتهاء الهوية", contact: "بيانات التواصل",
    email: "البريد الإلكتروني", phone: "الهاتف", customerCode: "كود العميل", documents: "المستندات", compliance: "مكافحة غسل الأموال والمخاطر",
    noAml: "لا توجد نتيجة فحص لمكافحة غسل الأموال.", riskProfile: "ملف المخاطر", score: "الدرجة", decision: "اتخاذ القرار", rejectionReason: "سبب الرفض",
    rejectionPlaceholder: "اكتب سبب الرفض بدقة وما الذي يجب على العميل تصحيحه...", approve: "اعتماد التحقق", reject: "رفض التحقق", approvalHelp: "الاعتماد يؤكد الهوية ويفعّل ملف العميل المرتبط.",
    rejectedReason: "سبب الرفض", completed: "اكتملت مراجعة هذا الطلب.", nextCustomer: "الخطوة التالية: ارجع إلى ملف العميل لمتابعة عملياته.",
    requiredReason: "اكتب سبب الرفض قبل رفض الطلب.", actionFailed: "تعذر حفظ قرار التحقق.", loading: "جارٍ تحميل بيانات المراجعة...",
    submittedStatus: "مقدم", reviewStatus: "قيد المراجعة", approvedStatus: "معتمد", rejectedStatus: "مرفوض", expiredStatus: "منتهي", pendingStatus: "معلق",
    low: "منخفضة", medium: "متوسطة", high: "عالية", critical: "حرجة", basic: "أساسي", intermediate: "متوسط", premium: "متقدم", missing: "ناقص", ready: "مكتمل",
  },
} as const

function unpack<T>(response: any): T {
  return (response?.data?.data ?? response?.data ?? response) as T
}

function nameOf(row: KycApplicationDTO) {
  return row.user?.full_name || row.user?.email || row.user?.phone || row.customer_code || row.user_id.slice(0, 8)
}

function riskFromScore(score: string | number | null | undefined) {
  const value = Number(score ?? 0)
  if (value >= 90) return "critical"
  if (value >= 70) return "high"
  if (value >= 40) return "medium"
  return "low"
}

export default function KycPage() {
  const { i18n } = useTranslation()
  const t = copy[i18n.language?.startsWith("ar") ? "ar" : "en"]
  const router = useRouter()
  const searchParams = useSearchParams()
  const { items, isLoading, fetchItems } = useKyc()
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [query, setQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [documents, setDocuments] = useState<KycDocument[]>([])
  const [screenings, setScreenings] = useState<AmlScreening[]>([])
  const [riskProfile, setRiskProfile] = useState<RiskProfile | null>(null)
  const [detailLoading, setDetailLoading] = useState(false)
  const [rejectReason, setRejectReason] = useState("")
  const [actionError, setActionError] = useState<string | null>(null)
  const [isActionLoading, setIsActionLoading] = useState(false)
  const [preview, setPreview] = useState<{ document: KycDocument; url: string; mimeType: string } | null>(null)
  const [previewLoadingId, setPreviewLoadingId] = useState<string | null>(null)
  const [documentActionId, setDocumentActionId] = useState<string | null>(null)
  const [previewExpanded, setPreviewExpanded] = useState(false)

  useEffect(() => { fetchItems(1, 100, "", { include: "user" }) }, [fetchItems])

  useEffect(() => () => {
    if (preview?.url) URL.revokeObjectURL(preview.url)
  }, [preview?.url])

  useEffect(() => {
    if (!items.length || selectedId) return
    const customerId = searchParams.get("customer")
    setSelectedId(items.find((item) => item.customer_id === customerId)?.id ?? items[0].id)
  }, [items, searchParams, selectedId])

  const filteredItems = useMemo(() => {
    const term = query.trim().toLowerCase()
    return items.filter((row) => {
      const matchesStatus = statusFilter === "all" || row.status === statusFilter
      const haystack = [row.id, row.customer_code, row.user?.full_name, row.user?.email, row.user?.phone].filter(Boolean).join(" ").toLowerCase()
      return matchesStatus && (!term || haystack.includes(term))
    })
  }, [items, query, statusFilter])

  const selected = items.find((row) => row.id === selectedId) ?? null
  const canReview = selected?.status === "submitted" || selected?.status === "under_review" || selected?.status === "pending"

  useEffect(() => {
    if (!selected) return
    let active = true
    setDetailLoading(true)
    setRejectReason("")
    setActionError(null)
    Promise.all([
      api.get(ENDPOINTS.KYC.DOCUMENTS(selected.id)).then((res) => unpack<KycDocument[]>(res)).catch(() => []),
      api.get(ENDPOINTS.KYC.AML_BY_USER(selected.user_id)).then((res) => unpack<AmlScreening[]>(res)).catch(() => []),
      api.get(ENDPOINTS.KYC.RISK_PROFILE(selected.user_id)).then((res) => unpack<RiskProfile>(res)).catch(() => null),
    ]).then(([docs, aml, risk]) => {
      if (!active) return
      setDocuments(Array.isArray(docs) ? docs : [])
      setScreenings(Array.isArray(aml) ? aml : [])
      setRiskProfile(risk)
      setDetailLoading(false)
    })
    return () => { active = false }
  }, [selected?.id, selected?.user_id])

  const refresh = async () => fetchItems(1, 100, "", { include: "user" })
  const openDocument = async (document: KycDocument) => {
    if (!selected) return
    setPreviewLoadingId(document.id)
    setActionError(null)
    try {
      const blob = await api.get(ENDPOINTS.KYC.DOCUMENT_CONTENT(selected.id, document.id), { responseType: "blob" }) as Blob
      const url = URL.createObjectURL(blob)
      setPreview({ document, url, mimeType: document.mime_type || blob.type })
    } catch (error: any) {
      setActionError(error?.response?.data?.detail || (i18n.language?.startsWith("ar") ? "تعذر فتح ملف المستند." : "The document file could not be opened."))
    } finally {
      setPreviewLoadingId(null)
    }
  }

  const closePreview = () => {
    if (preview?.url) URL.revokeObjectURL(preview.url)
    setPreviewExpanded(false)
    setPreview(null)
  }
  const reviewDocument = async (document: KycDocument, decision: "approve" | "reject") => {
    if (!selected) return
    const ar = i18n.language?.startsWith("ar")
    const reason = decision === "reject"
      ? window.prompt(ar ? "اكتب سبب رفض المستند وما المطلوب تصحيحه:" : "Enter the document rejection reason and required correction:")?.trim()
      : null
    if (decision === "reject" && !reason) return
    setDocumentActionId(document.id)
    setActionError(null)
    try {
      const response = await api.post(
        decision === "approve" ? ENDPOINTS.KYC.APPROVE_DOCUMENT(selected.id, document.id) : ENDPOINTS.KYC.REJECT_DOCUMENT(selected.id, document.id),
        decision === "reject" ? { rejection_reason: reason } : undefined,
      )
      const updated = unpack<KycDocument>(response)
      setDocuments((current) => current.map((item) => item.id === document.id ? updated : item))
      setPreview((current) => current?.document.id === document.id ? { ...current, document: updated } : current)
      await refresh()
    } catch (error: any) {
      setActionError(error?.response?.data?.detail || (ar ? "تعذر حفظ قرار المستند." : "The document decision could not be saved."))
    } finally {
      setDocumentActionId(null)
    }
  }
  const decide = async (decision: "approve" | "reject") => {
    if (!selected) return
    if (decision === "reject" && !rejectReason.trim()) { setActionError(t.requiredReason); return }
    setIsActionLoading(true)
    setActionError(null)
    try {
      await api.post(decision === "approve" ? ENDPOINTS.KYC.APPROVE(selected.id) : ENDPOINTS.KYC.REJECT(selected.id), decision === "reject" ? { rejection_reason: rejectReason.trim() } : undefined)
      await refresh()
      window.dispatchEvent(new Event("kyc-applications-updated"))
    } catch (error: any) {
      setActionError(error?.response?.data?.detail || t.actionFailed)
    } finally { setIsActionLoading(false) }
  }

  const statusMeta: Record<string, { label: string; tone: StatusTone }> = {
    submitted: { label: t.submittedStatus, tone: "pending" }, pending: { label: t.pendingStatus, tone: "pending" }, under_review: { label: t.reviewStatus, tone: "warning" },
    approved: { label: t.approvedStatus, tone: "success" }, rejected: { label: t.rejectedStatus, tone: "danger" }, expired: { label: t.expiredStatus, tone: "neutral" },
  }
  const riskMeta: Record<string, { label: string; tone: StatusTone }> = {
    low: { label: t.low, tone: "success" }, medium: { label: t.medium, tone: "warning" }, high: { label: t.high, tone: "danger" }, critical: { label: t.critical, tone: "danger" },
  }

  const columns: Column<KycApplicationDTO>[] = [
    { key: "application", header: t.application, cell: (row) => <span className="font-mono text-xs font-semibold">{row.id.slice(0, 8)}</span> },
    { key: "customer", header: t.customer, cell: (row) => <div className="flex items-center gap-2"><AvatarBadge name={nameOf(row)} size="sm" /><div><div className="text-[13px] font-medium">{nameOf(row)}</div><div className="text-[11px] text-muted-foreground">{row.customer_code ?? row.user?.email ?? "-"}</div></div></div> },
    { key: "level", header: t.level, cell: (row) => <span className="text-xs">{t[row.level as "basic" | "intermediate" | "premium"] ?? row.level}</span> },
    { key: "risk", header: t.risk, cell: (row) => { const risk = riskFromScore(row.risk_score); return <StatusBadge tone={riskMeta[risk].tone} size="sm">{riskMeta[risk].label}</StatusBadge> } },
    { key: "status", header: t.status, cell: (row) => <StatusBadge tone={statusMeta[row.status]?.tone ?? "neutral"} size="sm">{statusMeta[row.status]?.label ?? row.status}</StatusBadge> },
    { key: "submitted", header: t.submitted, cell: (row) => <span className="text-xs text-muted-foreground">{formatDateTime(row.submitted_at ?? row.created_at)}</span> },
  ]

  const pendingCount = items.filter((item) => ["submitted", "pending", "under_review"].includes(item.status)).length
  const checks = selected ? [
    { label: t.customerLinked, ok: Boolean(selected.customer_id) },
    { label: t.identityPresent, ok: Boolean(selected.identity_type && selected.identity_number) },
    { label: t.identityValid, ok: !selected.identity_expiry_date || new Date(selected.identity_expiry_date) >= new Date() },
    { label: t.documentsPresent, ok: documents.some((document) => document.status === "approved") && !documents.some((document) => document.status === "pending") },
  ] : []
  const documentsReady = documents.some((document) => document.status === "approved") && !documents.some((document) => document.status === "pending")

  return <div className="space-y-5">
    <PageHeader title={t.title} description={t.description} breadcrumbs={[{ label: t.customers, href: "/customers" }, { label: t.queue }]} />

    <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
      <KpiCard label={t.pending} value={String(pendingCount)} icon={Clock} tone="warning" />
      <KpiCard label={t.approved} value={String(items.filter((item) => item.status === "approved").length)} icon={FileCheck} tone="success" />
      <KpiCard label={t.rejected} value={String(items.filter((item) => item.status === "rejected").length)} icon={XCircle} tone="danger" />
      <KpiCard label={t.highRisk} value={String(items.filter((item) => Number(item.risk_score ?? 0) >= 70).length)} icon={ShieldAlert} tone="danger" accent />
    </div>

    <div className="grid gap-5 xl:grid-cols-[minmax(0,1fr)_500px]">
      <SectionCard title={t.queue} padded={false}>
        <div className="flex flex-col gap-3 border-b border-border p-4 sm:flex-row">
          <label className="relative flex-1"><Search className="absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" /><input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t.search} className="h-10 w-full rounded-md border border-border bg-background ps-9 pe-3 text-sm outline-none focus:border-gold-500" /></label>
          <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} className="h-10 rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-gold-500">
            <option value="all">{t.allStatuses}</option><option value="submitted">{t.submittedStatus}</option><option value="under_review">{t.reviewStatus}</option><option value="approved">{t.approvedStatus}</option><option value="rejected">{t.rejectedStatus}</option>
          </select>
        </div>
        {isLoading && !items.length ? <div className="p-10 text-center text-sm text-muted-foreground">{t.loading}</div> : filteredItems.length ? <DataTable columns={columns} data={filteredItems} rowKey={(row) => row.id} activeRowKey={selected?.id} onRowClick={(row) => setSelectedId(row.id)} /> : <div className="p-10 text-center text-sm text-muted-foreground">{t.noCases}</div>}
      </SectionCard>

      <SectionCard title={selected ? `${t.review} ${selected.id.slice(0, 8)}` : t.review}>
        {!selected ? <p className="text-sm text-muted-foreground">{t.selectCase}</p> : <div className="space-y-5">
          <div className="flex items-start justify-between gap-3 border-b border-border pb-4">
            <div className="flex min-w-0 items-center gap-3"><AvatarBadge name={nameOf(selected)} /><div className="min-w-0"><div className="truncate font-semibold">{nameOf(selected)}</div><div className="text-xs text-muted-foreground">{selected.customer_code ?? t.linkedCustomer}</div></div></div>
            {selected.customer_id && <Button variant="outline" size="sm" onClick={() => router.push(`/customers/${selected.customer_id}`)}><ExternalLink className="h-4 w-4" />{t.openCustomer}</Button>}
          </div>

          <section><Heading icon={ArrowUpLeft} text={t.workflow} /><div className="grid grid-cols-4 gap-1 text-center text-[11px] text-muted-foreground">{[t.stepCustomer, t.stepIdentity, t.stepCompliance, t.stepDecision].map((step, index) => <div key={step} className="border-t-2 border-gold-400 pt-2"><span className="mb-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-gold-100 font-semibold text-gold-800">{index + 1}</span><div>{step}</div></div>)}</div></section>

          {actionError && <div className="flex gap-2 rounded-md border border-red-200 bg-red-50 p-3 text-xs text-red-700"><AlertTriangle className="h-4 w-4 shrink-0" />{actionError}</div>}
          {selected.rejection_reason && <div className="rounded-md border border-red-200 bg-red-50 p-3"><div className="text-xs font-semibold text-red-700">{t.rejectedReason}</div><p className="mt-1 text-xs text-red-700">{selected.rejection_reason}</p></div>}

          <section><Heading icon={CheckCircle2} text={t.readiness} /><div className="grid grid-cols-2 gap-x-4 gap-y-2">{checks.map((check) => <div key={check.label} className="flex items-center gap-2 text-xs">{check.ok ? <CheckCircle2 className="h-4 w-4 text-emerald-600" /> : <AlertTriangle className="h-4 w-4 text-amber-600" />}<span>{check.label}</span><span className="ms-auto text-[11px] text-muted-foreground">{check.ok ? t.ready : t.missing}</span></div>)}</div></section>

          <section><Heading icon={UserRound} text={t.identity} /><div className="grid grid-cols-2 gap-x-5 gap-y-3"><Fact label={t.identityType} value={selected.identity_type} /><Fact label={t.identityNumber} value={selected.identity_number} mono /><Fact label={t.identityExpiry} value={selected.identity_expiry_date ? formatDateTime(selected.identity_expiry_date) : null} /><Fact label={t.customerCode} value={selected.customer_code} mono /><Fact label={t.email} value={selected.user?.email} /><Fact label={t.phone} value={selected.user?.phone} /></div></section>

          <section><Heading icon={FileText} text={`${t.documents} (${documents.length})`} />{detailLoading ? <p className="text-xs text-muted-foreground">{t.loading}</p> : !documents.length ? <p className="rounded-md border border-amber-200 bg-amber-50 p-3 text-xs text-amber-800">{t.noDocuments}</p> : <div className="divide-y divide-border border-y border-border">{documents.map((doc) => <div key={doc.id} className="py-2.5"><div className="flex items-center justify-between gap-3"><div className="min-w-0"><div className="truncate text-xs font-medium">{doc.file_name || doc.document_type}</div><div className="font-mono text-[11px] text-muted-foreground">{doc.document_type} · {doc.document_number ?? "-"}</div></div><div className="flex shrink-0 items-center gap-2"><StatusBadge tone={doc.status === "approved" ? "success" : doc.status === "rejected" ? "danger" : "pending"} size="sm">{doc.status}</StatusBadge><Button type="button" variant="outline" size="sm" isLoading={previewLoadingId === doc.id} onClick={() => openDocument(doc)}><Eye className="h-4 w-4" />{i18n.language?.startsWith("ar") ? "معاينة" : "Preview"}</Button>{canReview && doc.status === "pending" && <><Button type="button" variant="outline" size="sm" isLoading={documentActionId === doc.id} onClick={() => reviewDocument(doc, "approve")} className="border-emerald-200 text-emerald-700"><CheckCircle2 className="h-4 w-4" /><span className="sr-only">{i18n.language?.startsWith("ar") ? "اعتماد المستند" : "Approve document"}</span></Button><Button type="button" variant="outline" size="sm" disabled={documentActionId === doc.id} onClick={() => reviewDocument(doc, "reject")} className="border-red-200 text-red-700"><XCircle className="h-4 w-4" /><span className="sr-only">{i18n.language?.startsWith("ar") ? "رفض المستند" : "Reject document"}</span></Button></>}</div></div>{doc.rejection_reason && <p className="mt-2 text-xs text-red-700">{doc.rejection_reason}</p>}</div>)}</div>}</section>

          <section><Heading icon={ShieldAlert} text={t.compliance} /><div className="grid grid-cols-2 gap-4"><Fact label={t.riskProfile} value={riskProfile?.risk_level ?? riskFromScore(selected.risk_score)} /><Fact label={t.score} value={String(riskProfile?.risk_score ?? selected.risk_score ?? 0)} /> </div>{!screenings.length ? <p className="mt-3 text-xs text-muted-foreground">{t.noAml}</p> : <div className="mt-3 divide-y divide-border border-y border-border">{screenings.map((screening) => <div key={screening.id} className="flex items-center justify-between py-2 text-xs"><span>{screening.screening_type} · {screening.provider ?? "-"}</span><StatusBadge tone={screening.status === "clear" || screening.status === "passed" ? "success" : "warning"} size="sm">{screening.status}</StatusBadge></div>)}</div>}</section>

          {canReview ? <section><Heading icon={FileCheck} text={t.decision} /><p className="mb-3 text-xs text-muted-foreground">{documentsReady ? t.approvalHelp : (i18n.language?.startsWith("ar") ? "عاين كل مستند واعتمده أو ارفضه أولاً. يتطلب اعتماد KYC مستنداً معتمداً واحداً على الأقل دون مستندات معلقة." : "Preview and approve or reject every document first. Final KYC approval requires at least one approved document and no pending documents.")}</p><label className="block text-xs font-medium"><span>{t.rejectionReason}</span><textarea value={rejectReason} onChange={(e) => setRejectReason(e.target.value)} placeholder={t.rejectionPlaceholder} className="mt-1.5 min-h-20 w-full resize-y rounded-md border border-border bg-background p-3 text-sm outline-none focus:border-gold-500" /></label><div className="mt-3 flex gap-2"><Button variant="danger" className="flex-1" isLoading={isActionLoading} onClick={() => decide("reject")}><XCircle className="h-4 w-4" />{t.reject}</Button><Button className="flex-1" isLoading={isActionLoading} disabled={!documentsReady} onClick={() => decide("approve")}><FileCheck className="h-4 w-4" />{t.approve}</Button></div></section> : <div className="rounded-md border border-border bg-muted/30 p-3 text-xs"><div className="font-semibold">{t.completed}</div><div className="mt-1 text-muted-foreground">{t.nextCustomer}</div></div>}
        </div>}
      </SectionCard>
    </div>

    <Modal
      open={Boolean(preview)}
      onClose={closePreview}
      title={i18n.language?.startsWith("ar") ? "مقارنة مستند الهوية" : "Compare identity document"}
      description={preview?.document.file_name || preview?.document.document_type}
      size="lg"
    >
      {preview && selected && <div className="grid h-[68vh] min-h-[480px] gap-4 md:grid-cols-[minmax(0,1fr)_260px]">
        <div className="group relative flex min-h-0 items-center justify-center overflow-hidden rounded-md border border-border bg-neutral-100">
          {preview.mimeType === "application/pdf" ? <iframe src={preview.url} title={preview.document.file_name || "KYC document"} className="h-full w-full bg-white" /> : preview.mimeType.startsWith("image/") ? <button type="button" onClick={() => setPreviewExpanded(true)} className="flex h-full w-full cursor-zoom-in items-center justify-center" title={i18n.language?.startsWith("ar") ? "تكبير الصورة" : "Maximize image"}><img src={preview.url} alt={preview.document.file_name || "KYC document"} className="max-h-full max-w-full object-contain" /></button> : <div className="p-6 text-center text-sm text-muted-foreground">{i18n.language?.startsWith("ar") ? "لا يمكن عرض هذا النوع داخل المتصفح." : "This file type cannot be previewed in the browser."}</div>}
          {(preview.mimeType === "application/pdf" || preview.mimeType.startsWith("image/")) && <button type="button" onClick={() => setPreviewExpanded(true)} className="absolute end-3 top-3 z-10 inline-flex h-9 w-9 items-center justify-center rounded-md border border-border bg-white/95 text-foreground shadow-sm hover:bg-white" title={i18n.language?.startsWith("ar") ? "عرض بملء الشاشة" : "View full screen"}><Maximize2 className="h-4 w-4" /></button>}
        </div>
        <aside className="overflow-y-auto border-s border-border ps-4">
          <h3 className="mb-4 text-sm font-semibold">{i18n.language?.startsWith("ar") ? "البيانات المطلوب مطابقتها" : "Submitted data to compare"}</h3>
          <div className="space-y-4"><Fact label={t.customer} value={nameOf(selected)} /><Fact label={t.identityType} value={selected.identity_type} /><Fact label={t.identityNumber} value={selected.identity_number} mono /><Fact label={t.identityExpiry} value={selected.identity_expiry_date ? formatDateTime(selected.identity_expiry_date) : null} /><div className="border-t border-border pt-4"><Fact label={i18n.language?.startsWith("ar") ? "نوع المستند" : "Document type"} value={preview.document.document_type} /><div className="mt-3"><Fact label={i18n.language?.startsWith("ar") ? "رقم المستند" : "Document number"} value={preview.document.document_number} mono /></div><div className="mt-3"><Fact label={i18n.language?.startsWith("ar") ? "حالة المستند" : "Document status"} value={preview.document.status} /></div></div></div>
          <a href={preview.url} download={preview.document.file_name || "kyc-document"} className="mt-6 inline-flex h-9 w-full items-center justify-center gap-2 rounded-md border border-border bg-background text-xs font-medium hover:bg-muted"><Download className="h-4 w-4" />{i18n.language?.startsWith("ar") ? "تنزيل نسخة" : "Download copy"}</a>
          {canReview && preview.document.status === "pending" && <div className="mt-3 grid grid-cols-2 gap-2 border-t border-border pt-3">
            <Button type="button" variant="danger" size="sm" disabled={documentActionId === preview.document.id} onClick={() => reviewDocument(preview.document, "reject")}><XCircle className="h-4 w-4" />{i18n.language?.startsWith("ar") ? "رفض المستند" : "Reject document"}</Button>
            <Button type="button" size="sm" isLoading={documentActionId === preview.document.id} onClick={() => reviewDocument(preview.document, "approve")}><CheckCircle2 className="h-4 w-4" />{i18n.language?.startsWith("ar") ? "اعتماد المستند" : "Approve document"}</Button>
          </div>}
          {preview.document.status !== "pending" && <div className={`mt-3 rounded-md border p-3 text-center text-xs font-semibold ${preview.document.status === "approved" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-red-200 bg-red-50 text-red-700"}`}>{preview.document.status === "approved" ? (i18n.language?.startsWith("ar") ? "تم اعتماد هذا المستند" : "This document is approved") : (i18n.language?.startsWith("ar") ? "تم رفض هذا المستند" : "This document is rejected")}</div>}
        </aside>
      </div>}
    </Modal>

    {previewExpanded && preview && <div className="fixed inset-0 z-[80] flex flex-col bg-black/95" role="dialog" aria-modal="true">
      <div className="flex h-14 shrink-0 items-center justify-between border-b border-white/15 px-4 text-white">
        <div className="min-w-0"><div className="truncate text-sm font-semibold">{preview.document.file_name || preview.document.document_type}</div><div className="text-[11px] text-white/60">{preview.document.document_type} · {preview.document.document_number || "-"}</div></div>
        <button type="button" onClick={() => setPreviewExpanded(false)} className="inline-flex h-9 items-center gap-2 rounded-md border border-white/20 px-3 text-xs font-medium hover:bg-white/10" title={i18n.language?.startsWith("ar") ? "تصغير" : "Exit full screen"}><Minimize2 className="h-4 w-4" />{i18n.language?.startsWith("ar") ? "تصغير" : "Minimize"}</button>
      </div>
      <div className="min-h-0 flex-1 p-3">
        {preview.mimeType === "application/pdf" ? <iframe src={preview.url} title={preview.document.file_name || "KYC document full screen"} className="h-full w-full rounded-md bg-white" /> : <button type="button" onClick={() => setPreviewExpanded(false)} className="flex h-full w-full cursor-zoom-out items-center justify-center"><img src={preview.url} alt={preview.document.file_name || "KYC document"} className="max-h-full max-w-full object-contain" /></button>}
      </div>
    </div>}
  </div>
}

function Heading({ icon: Icon, text }: { icon: typeof FileCheck; text: string }) {
  return <div className="mb-3 flex items-center gap-2 text-xs font-semibold"><Icon className="h-4 w-4 text-gold-600" /><span>{text}</span></div>
}

function Fact({ label, value, mono }: { label: string; value: string | null | undefined; mono?: boolean }) {
  return <div><div className="text-[11px] text-muted-foreground">{label}</div><div className={mono ? "mt-0.5 break-all font-mono text-xs" : "mt-0.5 break-words text-xs font-medium"}>{value || "-"}</div></div>
}
