'use client'

import { useState, useEffect } from "react"
import { useRedemptions } from "@/hooks/useRedemptions"
import type { DeliveryOrderDTO } 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 { Package, Truck, MapPin, CheckCircle2, Timer } from "lucide-react"
import { fmtGrams, formatDate, formatDateTime } from "@/lib/format"
import i18n from "@/lib/i18n";

const statusMap: Record<string, { label: string; tone: StatusTone }> = {
  pending: { label: i18n.t('app.admin.redemptions.page.text_1'), tone: "pending" },
  reserved: { label: i18n.t('app.admin.redemptions.page.text_2'), tone: "info" },
  shipped: { label: i18n.t('app.admin.redemptions.page.text_3'), tone: "processing" },
  delivered: { label: i18n.t('app.admin.redemptions.page.text_4'), tone: "success" },
  blocked: { label: i18n.t('app.admin.redemptions.page.text_5'), tone: "danger" },
  cancelled: { label: i18n.t('app.admin.redemptions.page.text_6'), tone: "neutral" },
}

export default function RedemptionsPage() {
  const { items: rows, totalCount, fetchItems, isLoading } = useRedemptions()
  useEffect(() => { fetchItems() }, [fetchItems])
  
  const [shippedCount, setShippedCount] = useState(0)
  const [deliveredCount, setDeliveredCount] = useState(0)
  const [pendingCount, setPendingCount] = useState(0)
  const [selectedId, setSelectedId] = useState<string | null>(null)
  useEffect(() => {
    let s = 0, d = 0, p = 0;
    rows.forEach(r => {
      if (r.status === 'handed_over' || r.status === 'shipped') s++;
      else if (r.status === 'completed' || r.status === 'delivered') d++;
      else p++;
    });
    setShippedCount(s); setDeliveredCount(d); setPendingCount(p);
  }, [rows]);

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

  const columns: Column<DeliveryOrderDTO>[] = [
    { key: "code", header: i18n.t('app.admin.redemptions.page.text_7'), cell: (r) => <span className="font-mono text-[12.5px] font-semibold">{r.order_number}</span> },
    { key: "customer", header: i18n.t('app.admin.redemptions.page.text_8'), cell: (r) => <span className="text-[13px]">{r.client_name || r.client_user_id?.slice(0, 8)}</span> },
    { key: "product", header: i18n.t('app.admin.redemptions.page.text_9'), cell: (r) => <span className="text-[12.5px]">{"Gold Bar"} × {1}</span> },
    { key: "weight", header: i18n.t('app.admin.redemptions.page.text_10'), cell: (r) => <span className="font-mono tabular-nums text-[13px] font-semibold">{fmtGrams(Number(r.grams) || 0)}</span> },
    { key: "status", header: i18n.t('app.admin.redemptions.page.text_11'), 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.redemptions.page.text_12'), cell: (r) => <span className="text-[12px] text-muted-foreground">{formatDate(r.created_at)}</span> },
  ]

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

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.redemptions.page.text_17')} value={String(totalCount)} icon={Package} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.redemptions.page.text_18')} value={String(shippedCount)} icon={Truck} tone="processing" />
        <KpiCard label={i18n.t('app.admin.redemptions.page.text_19')} value={String(deliveredCount)} icon={CheckCircle2} tone="success" />
        <KpiCard label={i18n.t('app.admin.redemptions.page.text_20')} value={String(pendingCount)} icon={Timer} tone="warning" />
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_420px]">
        <SectionCard title={i18n.t('app.admin.redemptions.page.text_21')} padded={false}>
          {rows.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.redemptions.page.text_32')}</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.redemptions.page.text_request', { order_number: selected.order_number }) : i18n.t('app.admin.redemptions.page.text_22')}>
          {selected ? (
            <div className="space-y-4">
              <div className="rounded-lg border border-gold-200 bg-gradient-to-br from-gold-50/60 to-card p-4">
                <p className="text-[13.5px] font-semibold">{"Gold Bar"}</p>
                <p className="text-[12.5px] text-muted-foreground mt-0.5">
                  {1} {i18n.t('app.admin.redemptions.page.text_33')}{fmtGrams((Number(selected.grams) || 0) / 1)} {i18n.t('app.admin.redemptions.page.text_34')}{selected.purity ?? "99.99"}%
                </p>
                <div className="mt-3 pt-3 border-t border-gold-200/60">
                  <p className="text-[11.5px] uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.redemptions.page.text_35')}</p>
                  <p className="font-mono text-[18px] font-bold tabular-nums mt-0.5">{fmtGrams(Number(selected.grams) || 0)}</p>
                </div>
              </div>

              <div className="rounded-lg border border-border bg-muted/30 p-3 space-y-2">
                <Row k={i18n.t('app.admin.redemptions.page.text_23')} v={selected.client_name || selected.client_user_id?.slice(0, 8) || "—"} />
                <Row k={i18n.t('app.admin.redemptions.page.text_24')} v={selected.vault_id?.slice(0, 8) || "—"} />
                <Row k={i18n.t('app.admin.redemptions.page.text_25')} v={"N/A (Pickup)"} />
                <Row k={i18n.t('app.admin.redemptions.page.text_26')} v={"N/A"} mono />
                <Row k={i18n.t('app.admin.redemptions.page.text_27')} v={"N/A"} />
              </div>

              <div>
                <p className="text-[12px] font-semibold uppercase tracking-wide text-muted-foreground mb-2">{i18n.t('app.admin.redemptions.page.text_36')}</p>
                <div className="space-y-2">
                  <Timeline icon={<Package className="h-3.5 w-3.5" />} label={i18n.t('app.admin.redemptions.page.text_28')} date={selected.created_at} done />
                  <Timeline icon={<CheckCircle2 className="h-3.5 w-3.5" />} label={i18n.t('app.admin.redemptions.page.text_29')} done={selected.status !== "pending"} />
                  <Timeline icon={<Truck className="h-3.5 w-3.5" />} label={i18n.t('app.admin.redemptions.page.text_30')} date={selected.handed_over_at} done={!!selected.handed_over_at} />
                  <Timeline icon={<MapPin className="h-3.5 w-3.5" />} label={i18n.t('app.admin.redemptions.page.text_31')} date={selected.completed_at} done={!!selected.completed_at} />
                </div>
              </div>
            </div>
          ) : (
            <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.redemptions.page.text_37')}</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 text-[12.5px]">
      <span className="text-muted-foreground shrink-0">{k}</span>
      <span className={`text-right ${mono ? "font-mono" : ""}`}>{v}</span>
    </div>
  )
}

function Timeline({ icon, label, date, done }: { icon: React.ReactNode; label: string; date?: string | null; done?: boolean }) {
  return (
    <div className="flex items-center gap-2.5">
      <div className={`flex h-6 w-6 items-center justify-center rounded-full ${done ? "bg-emerald-100 text-emerald-700" : "bg-muted text-muted-foreground"}`}>{icon}</div>
      <div className="flex-1 flex items-center justify-between">
        <span className={`text-[12.5px] ${done ? "font-semibold text-foreground" : "text-muted-foreground"}`}>{label}</span>
        {date && <span className="text-[11px] text-muted-foreground">{formatDateTime(date)}</span>}
      </div>
    </div>
  )
}