'use client'

import { useState } from "react"
import { PageHeader } from "@/components/ui/page-header"
import { KpiCard } from "@/components/ui/kpi-card"
import { SectionCard } from "@/components/ui/section-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { Scale, AlertTriangle, CheckCircle2, Clock, Loader2 } from "lucide-react"
import { fmtMoney } from "@/lib/format"
import { useReconciliation, type ReconciliationExceptionRead } from "@/hooks/useReconciliation"
import { useEffect, useMemo } from "react"
import i18n from "@/lib/i18n";

type ExcRow = {
  id: string
  exception_code: string
  source: string
  transaction_ref: string | null
  internal_value: number | null
  external_value: number | null
  difference: number | null
  severity: string
  status: string
  age_hours: number
  suggested_cause: string | null
  assigned_to: string | null
}

const sevTone: Record<string, StatusTone> = { low: "info", medium: "warning", high: "danger", critical: "danger" }
const sevLabel: Record<string, string> = { low: i18n.t('app.admin.reconciliation.page.text_1'), medium: i18n.t('app.admin.reconciliation.page.text_2'), high: i18n.t('app.admin.reconciliation.page.text_3'), critical: i18n.t('app.admin.reconciliation.page.text_4') }
const statusTone: Record<string, StatusTone> = { under_review: "warning", resolved: "success", escalated: "danger" }
const statusLabel: Record<string, string> = { under_review: i18n.t('app.admin.reconciliation.page.text_5'), resolved: i18n.t('app.admin.reconciliation.page.text_6'), escalated: i18n.t('app.admin.reconciliation.page.text_7') }

export default function ReconciliationPage() {
  const { items, isLoading, fetchItems } = useReconciliation()

  useEffect(() => {
    fetchItems()
  }, [fetchItems])

  const rows = items || []
  const totalCount = rows.length
  const openCount = rows.filter(r => r.status === "under_review").length
  const resolvedCount = rows.filter(r => r.status === "resolved").length
  const criticalCount = rows.filter(r => r.severity === "critical").length

  const selected = rows.find((r) => r.severity === "critical") ?? rows[0]

  const columns: Column<ReconciliationExceptionRead>[] = [
    { key: "code", header: i18n.t('app.admin.reconciliation.page.text_8'), cell: (r) => <span className="font-mono text-[12.5px] font-semibold">{r.exception_code}</span> },
    { key: "source", header: i18n.t('app.admin.reconciliation.page.text_9'), cell: (r) => <span className="text-[12.5px]">{r.source}</span> },
    { key: "ref", header: i18n.t('app.admin.reconciliation.page.text_10'), cell: (r) => <span className="font-mono text-[11.5px] text-muted-foreground">{r.transaction_ref ?? "—"}</span> },
    { key: "diff", header: i18n.t('app.admin.reconciliation.page.text_11'), cell: (r) => <span className={`font-mono tabular-nums text-[13px] font-semibold ${Math.abs(Number(r.difference ?? 0)) > 1000 ? "text-red-600" : "text-amber-700"}`}>{fmtMoney(Math.abs(Number(r.difference ?? 0)))}</span> },
    { key: "severity", header: i18n.t('app.admin.reconciliation.page.text_12'), cell: (r) => <StatusBadge tone={sevTone[r.severity] ?? "neutral"} size="sm">{sevLabel[r.severity] ?? r.severity}</StatusBadge> },
    { key: "age", header: i18n.t('app.admin.reconciliation.page.text_13'), cell: (r) => <span className={`text-[12px] ${r.age_hours > 24 ? "text-red-600 font-semibold" : "text-muted-foreground"}`}>{r.age_hours}{i18n.t('app.admin.reconciliation.page.text_31')}</span> },
    { key: "status", header: i18n.t('app.admin.reconciliation.page.text_14'), cell: (r) => <StatusBadge tone={statusTone[r.status] ?? "neutral"} size="sm">{statusLabel[r.status] ?? r.status}</StatusBadge> },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title={i18n.t('app.admin.reconciliation.page.text_15')}
        description={i18n.t('app.admin.reconciliation.page.text_16')}
        breadcrumbs={[{ label: i18n.t('app.admin.reconciliation.page.text_17'), href: "#" }, { label: i18n.t('app.admin.reconciliation.page.text_18') }]}
      />

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.reconciliation.page.text_19')} value={String(totalCount)} icon={Scale} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.reconciliation.page.text_20')} value={String(openCount)} icon={Clock} tone="warning" />
        <KpiCard label={i18n.t('app.admin.reconciliation.page.text_21')} value={String(criticalCount)} icon={AlertTriangle} tone="danger" />
        <KpiCard label={i18n.t('app.admin.reconciliation.page.text_22')} value={String(resolvedCount)} icon={CheckCircle2} tone="success" />
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_400px]">
        <SectionCard title={i18n.t('app.admin.reconciliation.page.text_23')} padded={false}>
          {isLoading ? (
            <div className="flex justify-center items-center py-8"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
          ) : rows.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.reconciliation.page.text_32')}</div>
          ) : (
            <DataTable columns={columns} data={rows} rowKey={(r) => r.id} activeRowKey={selected?.id} />
          )}
        </SectionCard>

        <SectionCard title={selected ? selected.exception_code : i18n.t('app.admin.reconciliation.page.text_24')}>
          {selected ? (
            <div className="space-y-4">
              <div className="rounded-lg border border-red-200 bg-red-50 p-3.5 space-y-1">
                <p className="text-[11.5px] uppercase tracking-wider text-red-700 font-semibold">{i18n.t('app.admin.reconciliation.page.text_33')}</p>
                <p className="font-mono text-[22px] font-bold text-red-700 tabular-nums">{fmtMoney(Math.abs(Number(selected.difference ?? 0)))}</p>
                <p className="text-[11.5px] text-red-700">{i18n.t('app.admin.reconciliation.page.text_34')}{sevLabel[selected.severity]}</p>
              </div>
              <div className="rounded-lg border border-border bg-muted/30 p-3 space-y-2 text-[12.5px]">
                <Row k={i18n.t('app.admin.reconciliation.page.text_25')} v={selected.source} />
                <Row k={i18n.t('app.admin.reconciliation.page.text_26')} v={selected.transaction_ref ?? "—"} mono />
                <Row k={i18n.t('app.admin.reconciliation.page.text_27')} v={fmtMoney(selected.internal_value ?? 0)} />
                <Row k={i18n.t('app.admin.reconciliation.page.text_28')} v={fmtMoney(selected.external_value ?? 0)} />
                <Row k={i18n.t('app.admin.reconciliation.page.text_29')} v={i18n.t('app.admin.reconciliation.page.text_hours', { hours: selected.age_hours })} />
                <Row k={i18n.t('app.admin.reconciliation.page.text_30')} v={selected.assigned_to ?? "—"} />
              </div>
              {selected.suggested_cause && (
                <div className="rounded-lg border border-border bg-card p-3">
                  <p className="text-[11.5px] font-semibold uppercase tracking-wide text-muted-foreground mb-1">{i18n.t('app.admin.reconciliation.page.text_35')}</p>
                  <p className="text-[12.5px] leading-relaxed">{selected.suggested_cause}</p>
                </div>
              )}
              <div className="flex gap-2">
                <button className="flex-1 rounded-lg border border-border py-2 text-[13px] font-semibold hover:bg-muted transition">{i18n.t('app.admin.reconciliation.page.text_36')}</button>
                <button className="flex-1 rounded-lg bg-gold-500 py-2 text-[13px] font-semibold text-white hover:bg-gold-600 transition">{i18n.t('app.admin.reconciliation.page.text_37')}</button>
              </div>
            </div>
          ) : (
            <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.reconciliation.page.text_38')}</p>
          )}
        </SectionCard>
      </div>
    </div>
  )
}

function Row({ k, v, mono }: { k: string; v: string; mono?: boolean }) {
  return (
    <div className="flex items-center justify-between gap-3">
      <span className="text-muted-foreground">{k}</span>
      <span className={`text-right ${mono ? "font-mono" : ""}`}>{v}</span>
    </div>
  )
}