'use client'

import { useEffect, useState, useMemo } 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 { Percent, Layers, Gauge, Sparkles, Loader2 } from "lucide-react"
import { fmtMoney } from "@/lib/format"
import { useFeeRules, useTaxRules, FeeRuleDTO, TaxRuleDTO } from "@/hooks/useFees"
import i18n from "@/lib/i18n";

type FeeRow = { id: string; name: string; applies_to: string; fixed_amount: number | null; pct_amount: number | null; status: string; priority: number }
type CommRow = { id: string; name: string; rate_pct: number; min_tier: string; status: string }
type LimitRow = { tier: string; max_daily_buy: number; max_transfer: number | null; withdrawal_ceiling: number }

const statusMap: Record<string, StatusTone> = { active: "success", inactive: "neutral", paused: "warning" }
const tierLabel: Record<string, string> = { retail: i18n.t('app.admin.fees.page.text_1'), premium: i18n.t('app.admin.fees.page.text_2'), institutional: i18n.t('app.admin.fees.page.text_3') }

export default function FeesPage() {
  const { items: feeRulesData, isLoading: isLoadingFees, fetchItems: fetchFees } = useFeeRules()
  const { items: taxRulesData, isLoading: isLoadingTaxes, fetchItems: fetchTaxes } = useTaxRules()
  
  const [limits] = useState<LimitRow[]>([
    { tier: "retail", max_daily_buy: 10000, max_transfer: 5000, withdrawal_ceiling: 20000 },
    { tier: "premium", max_daily_buy: 50000, max_transfer: 25000, withdrawal_ceiling: 100000 },
    { tier: "institutional", max_daily_buy: 500000, max_transfer: null, withdrawal_ceiling: 1000000 },
  ]) // Still mocked or handled later

  useEffect(() => {
    fetchFees()
    fetchTaxes()
  }, [fetchFees, fetchTaxes])

  const fees: FeeRow[] = useMemo(() => feeRulesData.map((f: FeeRuleDTO) => ({
    id: f.id,
    name: f.name_ar,
    applies_to: f.applies_to,
    fixed_amount: f.fixed_amount,
    pct_amount: f.percent_value,
    status: f.is_active ? "active" : "inactive",
    priority: 1
  })), [feeRulesData])

  const comms: CommRow[] = useMemo(() => taxRulesData.map((t: TaxRuleDTO) => ({
    id: t.id,
    name: t.name_ar,
    rate_pct: t.percent_value,
    min_tier: t.tax_type,
    status: t.is_active ? "active" : "inactive",
  })), [taxRulesData])

  const avgPct = fees.length ? (fees.reduce((s, f) => s + Number(f.pct_amount ?? 0), 0) / fees.length).toFixed(2) : "—"

  const feeCols: Column<FeeRow>[] = [
    { key: "name", header: i18n.t('app.admin.fees.page.text_4'), cell: (r) => <span className="text-[13px] font-medium">{r.name}</span> },
    { key: "applies", header: i18n.t('app.admin.fees.page.text_5'), cell: (r) => <span className="text-[12.5px] text-muted-foreground">{r.applies_to}</span> },
    { key: "fixed", header: i18n.t('app.admin.fees.page.text_6'), cell: (r) => <span className="font-mono tabular-nums text-[12.5px]">{r.fixed_amount ? fmtMoney(r.fixed_amount) : "—"}</span> },
    { key: "pct", header: i18n.t('app.admin.fees.page.text_7'), cell: (r) => <span className="font-mono tabular-nums text-[12.5px]">{r.pct_amount ? `${r.pct_amount}%` : "—"}</span> },
    { key: "status", header: i18n.t('app.admin.fees.page.text_8'), cell: (r) => <StatusBadge tone={statusMap[r.status] ?? "neutral"} size="sm">{r.status === "active" ? i18n.t('app.admin.fees.page.text_9') : r.status}</StatusBadge> },
  ]

  const commCols: Column<CommRow>[] = [
    { key: "name", header: i18n.t('app.admin.fees.page.text_10'), cell: (r) => <span className="text-[13px] font-medium">{r.name}</span> },
    { key: "rate", header: i18n.t('app.admin.fees.page.text_11'), cell: (r) => <span className="font-mono tabular-nums text-[13px] font-semibold">{r.rate_pct}%</span> },
    { key: "tier", header: i18n.t('app.admin.fees.page.text_12'), cell: (r) => <span className="text-[12.5px]">{tierLabel[r.min_tier] ?? r.min_tier}</span> },
    { key: "status", header: i18n.t('app.admin.fees.page.text_13'), cell: (r) => <StatusBadge tone={statusMap[r.status] ?? "neutral"} size="sm">{r.status === "active" ? i18n.t('app.admin.fees.page.text_14') : r.status}</StatusBadge> },
  ]

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

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.fees.page.text_19')} value={String(fees.length)} icon={Layers} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.fees.page.text_20')} value={String(comms.length)} icon={Percent} tone="success" />
        <KpiCard label={i18n.t('app.admin.fees.page.text_21')} value={String(limits.length)} icon={Gauge} tone="info" />
        <KpiCard label={i18n.t('app.admin.fees.page.text_22')} value={avgPct as string} icon={Sparkles} tone="warning" />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <SectionCard title={i18n.t('app.admin.fees.page.text_23')} padded={false}>
          {isLoadingFees ? (
            <div className="flex justify-center items-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
          ) : fees.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.fees.page.text_30')}</div>
          ) : (
            <DataTable columns={feeCols} data={fees} rowKey={(r) => r.id} />
          )}
        </SectionCard>
        <SectionCard title={i18n.t('app.admin.fees.page.text_24')} padded={false}>
          {isLoadingTaxes ? (
            <div className="flex justify-center items-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
          ) : comms.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.fees.page.text_31')}</div>
          ) : (
            <DataTable columns={commCols} data={comms} rowKey={(r) => r.id} />
          )}
        </SectionCard>
      </div>

      <SectionCard title={i18n.t('app.admin.fees.page.text_25')}>
        {limits.length === 0 ? (
          <div className="py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.fees.page.text_32')}</div>
        ) : (
          <div className="grid gap-4 md:grid-cols-3">
            {limits.map((l) => (
              <div key={l.tier} className="rounded-lg border border-border bg-gradient-to-br from-gold-50/40 to-card p-4 space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-[13px] font-bold">{tierLabel[l.tier] ?? l.tier}</span>
                  <span className="text-[11px] uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.fees.page.text_33')}</span>
                </div>
                <Row k={i18n.t('app.admin.fees.page.text_26')} v={fmtMoney(l.max_daily_buy)} />
                <Row k={i18n.t('app.admin.fees.page.text_27')} v={l.max_transfer ? fmtMoney(l.max_transfer) : i18n.t('app.admin.fees.page.text_28')} />
                <Row k={i18n.t('app.admin.fees.page.text_29')} v={fmtMoney(l.withdrawal_ceiling)} />
              </div>
            ))}
          </div>
        )}
      </SectionCard>
    </div>
  )
}

function Row({ k, v }: { k: string; v: string }) {
  return (
    <div className="flex items-center justify-between border-t border-border/60 pt-2 text-[12.5px]">
      <span className="text-muted-foreground">{k}</span>
      <span className="font-mono tabular-nums font-semibold">{v}</span>
    </div>
  )
}