'use client'

import { useEffect, 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 { TrendingUp, Zap, Activity, Settings2, Rss, Loader2 } from "lucide-react"
import { fmtMoney, formatDateTime } from "@/lib/format"
import { usePricing } from "@/hooks/usePricing"
import i18n from "@/lib/i18n";

type SourceRow = { id: string; name: string; latency_ms: number; status: string; is_primary: boolean; priority: number }
type TickRow = { id: string; spot_price: number; buy_price: number; sell_price: number; spread_bps: number | null; source: string | null; captured_at: string }

const srcMap: Record<string, { label: string; tone: StatusTone }> = {
  operational: { label: i18n.t('app.admin.pricing.page.text_1'), tone: "success" },
  degraded: { label: i18n.t('app.admin.pricing.page.text_2'), tone: "warning" },
  down: { label: i18n.t('app.admin.pricing.page.text_3'), tone: "danger" },
}

export default function PricingPage() {
  const [sources] = useState<SourceRow[]>([
    { id: "SRC-1", name: "Bloomberg", latency_ms: 120, status: "operational", is_primary: true, priority: 1 },
    { id: "SRC-2", name: "Reuters", latency_ms: 155, status: "operational", is_primary: false, priority: 2 },
    { id: "SRC-3", name: "Local Feed", latency_ms: 240, status: "degraded", is_primary: false, priority: 3 },
  ])
  const [ticks] = useState<TickRow[]>([
    { id: "T-1", spot_price: 2345.50, buy_price: 2340.00, sell_price: 2355.00, spread_bps: 15.0, source: "Bloomberg", captured_at: new Date().toISOString() },
    { id: "T-2", spot_price: 2345.00, buy_price: 2339.50, sell_price: 2354.50, spread_bps: 15.0, source: "Reuters", captured_at: new Date(Date.now() - 60000).toISOString() },
    { id: "T-3", spot_price: 2342.20, buy_price: 2336.50, sell_price: 2351.00, spread_bps: 14.5, source: "Bloomberg", captured_at: new Date(Date.now() - 120000).toISOString() },
  ])
  
  const { items: spreadRules, isLoading, fetchItems } = usePricing()

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

  const latest = ticks[0]

  const sourceCols: Column<SourceRow>[] = [
    { key: "name", header: i18n.t('app.admin.pricing.page.text_4'), cell: (r) => <span className="text-[13px] font-medium">{r.name}{r.is_primary && <span className="mr-2 text-[10.5px] font-semibold text-gold-700">{i18n.t('app.admin.pricing.page.text_19')}</span>}</span> },
    { key: "priority", header: i18n.t('app.admin.pricing.page.text_5'), cell: (r) => <span className="font-mono text-[12.5px]">#{r.priority}</span> },
    { key: "latency", header: i18n.t('app.admin.pricing.page.text_6'), cell: (r) => <span className={`font-mono tabular-nums text-[12.5px] ${r.latency_ms > 200 ? "text-red-600" : ""}`}>{r.latency_ms}ms</span> },
    { key: "status", header: i18n.t('app.admin.pricing.page.text_7'), cell: (r) => <StatusBadge tone={srcMap[r.status]?.tone ?? "neutral"} size="sm">{srcMap[r.status]?.label ?? r.status}</StatusBadge> },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title={i18n.t('app.admin.pricing.page.text_8')}
        description={i18n.t('app.admin.pricing.page.text_9')}
        breadcrumbs={[{ label: i18n.t('app.admin.pricing.page.text_10'), href: "#" }, { label: i18n.t('app.admin.pricing.page.text_11') }]}
      />

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.pricing.page.text_12')} value={latest ? fmtMoney(latest.spot_price) : "—"} unit="USD/oz" icon={TrendingUp} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.pricing.page.text_13')} value={latest ? fmtMoney(latest.buy_price) : "—"} icon={Zap} tone="success" />
        <KpiCard label={i18n.t('app.admin.pricing.page.text_14')} value={latest ? fmtMoney(latest.sell_price) : "—"} icon={Activity} tone="info" />
        <KpiCard label={i18n.t('app.admin.pricing.page.text_15')} value={latest?.spread_bps?.toFixed(2) ?? "—"} icon={Settings2} tone="warning" />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <SectionCard title={i18n.t('app.admin.pricing.page.text_16')} icon={<Rss className="h-4 w-4 text-gold-600" />} padded={false}>
          {sources.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.pricing.page.text_20')}</div>
          ) : (
            <DataTable columns={sourceCols} data={sources} rowKey={(r) => r.id} />
          )}
        </SectionCard>

        <SectionCard title={i18n.t('app.admin.pricing.page.text_17')} padded={false}>
          {ticks.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.pricing.page.text_21')}</div>
          ) : (
            <table className="w-full text-right">
              <thead className="bg-muted/40 border-b border-border">
                <tr>
                  <th className="px-4 py-3 text-[11.5px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.pricing.page.text_22')}</th>
                  <th className="px-4 py-3 text-[11.5px] font-semibold uppercase tracking-wider text-muted-foreground">Spot</th>
                  <th className="px-4 py-3 text-[11.5px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.pricing.page.text_23')}</th>
                  <th className="px-4 py-3 text-[11.5px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.pricing.page.text_24')}</th>
                  <th className="px-4 py-3 text-[11.5px] font-semibold uppercase tracking-wider text-muted-foreground">bps</th>
                </tr>
              </thead>
              <tbody>
                {ticks.map((t) => (
                  <tr key={t.id} className="border-b border-border/70">
                    <td className="px-4 py-2.5 text-[11.5px] text-muted-foreground">{formatDateTime(t.captured_at)}</td>
                    <td className="px-4 py-2.5 font-mono tabular-nums text-[12.5px] font-semibold">{fmtMoney(t.spot_price)}</td>
                    <td className="px-4 py-2.5 font-mono tabular-nums text-[12.5px] text-emerald-600">{fmtMoney(t.buy_price)}</td>
                    <td className="px-4 py-2.5 font-mono tabular-nums text-[12.5px] text-red-600">{fmtMoney(t.sell_price)}</td>
                    <td className="px-4 py-2.5 font-mono tabular-nums text-[12.5px]">{t.spread_bps?.toFixed(2) ?? "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </SectionCard>
      </div>

      <SectionCard title={i18n.t('app.admin.pricing.page.text_18')} icon={<Settings2 className="h-4 w-4 text-gold-600" />}>
        {isLoading ? (
          <div className="flex justify-center items-center py-6"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
        ) : spreadRules.length === 0 ? (
          <div className="text-center py-6 text-[13px] text-muted-foreground">{i18n.t('app.admin.pricing.page.text_25')}</div>
        ) : (
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
            {spreadRules.map((rule) => (
              <div key={rule.id} className="rounded-lg border border-border bg-muted/20 p-4 text-[13px]">
                <h4 className="font-medium mb-3">{rule.name}</h4>
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">{i18n.t('app.admin.pricing.page.text_26')}</span>
                    <span className="font-mono text-emerald-600 font-medium">{rule.buy_spread_percent}%</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">{i18n.t('app.admin.pricing.page.text_27')}</span>
                    <span className="font-mono text-red-600 font-medium">{rule.sell_spread_percent}%</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">{i18n.t('app.admin.pricing.page.text_28')}</span>
                    <span className="font-mono">{rule.min_spread_amount}</span>
                  </div>
                  <div className="flex justify-between mt-2 pt-2 border-t border-border/50">
                    <span className="text-muted-foreground">{i18n.t('app.admin.pricing.page.text_29')}</span>
                    <span>{rule.is_active ? <span className="text-emerald-600">{i18n.t('app.admin.pricing.page.text_30')}</span> : <span className="text-red-600">{i18n.t('app.admin.pricing.page.text_31')}</span>}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </SectionCard>
    </div>
  )
}