'use client'

import { useState, useEffect } from "react"
import { useTransfers } from "@/hooks/useTransfers"
import type { TransferDTO } from "@/types"
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 { Send, CheckCircle2, Flag, ShieldAlert, ArrowLeftRight } from "lucide-react"
import { fmtGrams, fmtMoney, formatDateTime } from "@/lib/format"
import i18n from "@/lib/i18n";

const statusMap: Record<string, { label: string; tone: StatusTone }> = {
  draft: { label: i18n.t('app.admin.transfers.page.text_1'), tone: "neutral" },
  pending_approval: { label: i18n.t('app.admin.transfers.page.text_2'), tone: "warning" },
  approved: { label: i18n.t('app.admin.transfers.page.text_3'), tone: "info" },
  in_transit: { label: i18n.t('app.admin.transfers.page.text_4'), tone: "processing" },
  completed: { label: i18n.t('app.admin.transfers.page.text_5'), tone: "success" },
  cancelled: { label: i18n.t('app.admin.transfers.page.text_6'), tone: "neutral" },
  rejected: { label: i18n.t('app.admin.transfers.page.text_7'), tone: "danger" },
}

export default function TransfersPage() {
  const { items: rows, totalCount, fetchItems, isLoading, approveTransfer, rejectTransfer } = useTransfers()
  useEffect(() => { fetchItems() }, [fetchItems])
  
  const [successCount, setSuccessCount] = useState(0)
  const [pendingCount, setPendingCount] = useState(0)
  const [flaggedCount, setFlaggedCount] = useState(0)
  const [selectedId, setSelectedId] = useState<string | null>(null)
  useEffect(() => {
    let s = 0, p = 0, f = 0;
    rows.forEach(r => {
      if (r.status === 'completed') s++;
      else if (r.status === 'rejected' || r.status === 'cancelled') f++;
      else p++;
    });
    setSuccessCount(s); setPendingCount(p); setFlaggedCount(f);
  }, [rows]);

  const selected = selectedId ? rows.find((r) => r.id === selectedId) : rows[0]

  const columns: Column<TransferDTO>[] = [
    { key: "code", header: i18n.t('app.admin.transfers.page.text_8'), cell: (r) => <span className="font-mono text-[12.5px] font-semibold">{r.order_number}</span> },
    { key: "sender", header: i18n.t('app.admin.transfers.page.text_9'), cell: (r) => <span className="text-[13px]">{r.from_vault_name || r.from_vault_id?.slice(0, 8)}</span> },
    { key: "recipient", header: i18n.t('app.admin.transfers.page.text_10'), cell: (r) => <span className="text-[13px]">{r.to_vault_name || r.to_vault_id?.slice(0, 8)}</span> },
    {
      key: "qty",
      header: i18n.t('app.admin.transfers.page.text_11'),
      cell: (r) =>
        true ? (
          <span className="font-mono tabular-nums text-[13px] font-semibold">{fmtGrams(Number(r.total_weight) || 0)}</span>
        ) : (
          <span className="font-mono tabular-nums text-[13px] font-semibold">{fmtMoney(Number(r.total_weight) || 0)}</span>
        ),
    },
    { key: "status", header: i18n.t('app.admin.transfers.page.text_12'), cell: (r) => <StatusBadge tone={statusMap[r.status]?.tone ?? "neutral"} size="sm">{statusMap[r.status]?.label ?? r.status}</StatusBadge> },
    { key: "date", header: i18n.t('app.admin.transfers.page.text_13'), cell: (r) => <span className="text-[12px] text-muted-foreground">{formatDateTime(r.created_at)}</span> },
  ]

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

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.transfers.page.text_18')} value={String(totalCount)} icon={ArrowLeftRight} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.transfers.page.text_19')} value={String(successCount)} icon={CheckCircle2} tone="success" />
        <KpiCard label={i18n.t('app.admin.transfers.page.text_20')} value={String(pendingCount)} icon={Send} tone="warning" />
        <KpiCard label={i18n.t('app.admin.transfers.page.text_21')} value={String(flaggedCount)} icon={Flag} tone="danger" />
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_400px]">
        <SectionCard title={i18n.t('app.admin.transfers.page.text_22')} padded={false}>
          {rows.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.transfers.page.text_30')}</div>
          ) : (
            <DataTable columns={columns} data={rows} rowKey={(r) => r.id} activeRowKey={selected?.id} onRowClick={(r) => setSelectedId(r.id)} />
          )}
        </SectionCard>

        <SectionCard title={selected ? i18n.t('app.admin.transfers.page.text_transfer', { order_number: selected.order_number }) : i18n.t('app.admin.transfers.page.text_23')}>
          {selected ? (
            <div className="space-y-4">
              <div className="rounded-lg border border-border bg-gradient-to-br from-gold-50/40 to-card p-4">
                <div className="flex items-center justify-between mb-3">
                  <div className="text-right">
                    <p className="text-[11.5px] text-muted-foreground">{i18n.t('app.admin.transfers.page.text_31')}</p>
                    <p className="text-[13px] font-semibold">{selected.from_vault_name || selected.from_vault_id?.slice(0, 8)}</p>
                  </div>
                  <ArrowLeftRight className="h-4 w-4 text-gold-600" />
                  <div className="text-right">
                    <p className="text-[11.5px] text-muted-foreground">{i18n.t('app.admin.transfers.page.text_32')}</p>
                    <p className="text-[13px] font-semibold">{selected.to_vault_name || selected.to_vault_id?.slice(0, 8)}</p>
                  </div>
                </div>
                <div className="border-t border-border pt-3 text-center">
                  <p className="text-[11.5px] uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.transfers.page.text_33')}</p>
                  <p className="font-mono text-[20px] font-bold tabular-nums mt-1">
                    {true ? fmtGrams(Number(selected?.total_weight) || 0) : fmtMoney(Number(selected?.total_weight) || 0)}
                  </p>
                </div>
              </div>
              <div className="rounded-lg border border-border bg-muted/30 p-3 space-y-2.5">
                <CheckRow label={i18n.t('app.admin.transfers.page.text_24')} ok={true} />
                <CheckRow label={i18n.t('app.admin.transfers.page.text_25')} ok={true} />
                <CheckRow label={i18n.t('app.admin.transfers.page.text_26')} ok={selected?.priority !== "high" && selected?.priority !== "critical"} note={selected?.priority || "—"} />
              </div>

              <div className="flex gap-2">
                <button
                  onClick={() => rejectTransfer(selected.id, i18n.t('app.admin.transfers.page.text_27'))}
                  disabled={selected.status !== 'pending_approval' || isLoading}
                  className="flex-1 rounded-lg border border-red-200 bg-red-50 py-2 text-[13px] font-semibold text-red-700 hover:bg-red-100 transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {i18n.t('app.admin.transfers.page.text_34')}</button>
                <button
                  onClick={() => approveTransfer(selected.id)}
                  disabled={selected.status !== 'pending_approval' || isLoading}
                  className="flex-1 rounded-lg bg-gold-500 py-2 text-[13px] font-semibold text-white hover:bg-gold-600 transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {i18n.t('app.admin.transfers.page.text_35')}</button>
              </div>
            </div>
          ) : (
            <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.transfers.page.text_36')}</p>
          )}
        </SectionCard>
      </div>
    </div>
  )
}

function CheckRow({ label, ok, note }: { label: string; ok: boolean; note?: string }) {
  return (
    <div className="flex items-center justify-between text-[12.5px]">
      <span className="text-muted-foreground">{label}</span>
      <span className={`inline-flex items-center gap-1 ${ok ? "text-emerald-600" : "text-red-600"} font-semibold`}>
        {ok ? <CheckCircle2 className="h-3.5 w-3.5" /> : <Flag className="h-3.5 w-3.5" />}
        {note ?? (ok ? i18n.t('app.admin.transfers.page.text_28') : i18n.t('app.admin.transfers.page.text_29'))}
      </span>
    </div>
  )
}