'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { Eye, RefreshCw, Search, Key, CheckCircle2, AlertOctagon, Snowflake } from "lucide-react"
import { useTranslation } from "react-i18next"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { KpiCard } from "@/components/ui/kpi-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge } from "@/components/ui/status-badge"
import { Button } from "@/components/ui/button"
import { fmtGrams, formatDateTime } from "@/lib/format"

type Bar = {
  id: string
  bar_code: string
  serial_number: string | null
  metal_type: string
  purity_id: string | null
  weight: string
  weight_grams?: string
  status: string
  current_vault_id: string | null
  current_owner_type: string | null
  inspection_status: string | null
  purity_name: string | null
  vault_name: string | null
  branch_name: string | null
  current_inventory: string | null
  is_reserved: boolean
  total_cost: string | null
  last_movement_type: string | null
  last_movement_at: string | null
  created_at: string
}

const barStatusTone: Record<string, any> = {
  available: "success",
  reserved: "warning",
  blocked: "danger",
  in_transit: "processing",
  delivered: "info",
  sold: "neutral",
  pending_inspection: "pending",
  allocated_to_pool: "processing",
}

const registryStatuses = ["", "available", "reserved", "blocked", "in_transit", "delivered", "pending_inspection", "in_custody"]

const statusText: Record<string, { ar: string; en: string }> = {
  available: { ar: "متاحة", en: "Available" },
  reserved: { ar: "محجوزة", en: "Reserved" },
  blocked: { ar: "مجمّدة", en: "Blocked" },
  in_transit: { ar: "قيد النقل", en: "In transit" },
  delivered: { ar: "مسلّمة", en: "Delivered" },
  pending_inspection: { ar: "بانتظار الفحص", en: "Pending inspection" },
  in_custody: { ar: "في الأمانات", en: "In custody" },
}

export default function BullionBarsPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const [bars, setBars] = useState<Bar[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState("")
  const [statusFilter, setStatusFilter] = useState("")
  const [ownerFilter, setOwnerFilter] = useState("")

  const refresh = useCallback(async () => {
    setIsLoading(true)
    setError(null)
    try {
      const response = await api.get(ENDPOINTS.BULLION_BARS.LIST, {
        params: {
          registry: true,
          q: search || undefined,
          status: statusFilter || undefined,
          owner_type: ownerFilter || undefined,
          skip: 0,
          limit: 500,
        },
      })
      const data = response?.data ?? response
      setBars(Array.isArray(data) ? data : [])
    } catch (err: any) {
      setError(err?.message || "Failed to load bars")
    } finally {
      setIsLoading(false)
    }
  }, [ownerFilter, search, statusFilter])

  useEffect(() => {
    const timer = window.setTimeout(refresh, 300)
    return () => window.clearTimeout(timer)
  }, [refresh])

  const filtered = useMemo(() => bars, [bars])

  const columns: Column<Bar>[] = [
    {
      key: "code",
      header: language === "ar" ? "الباركود" : "Bar Code",
      cell: row => <span className="block max-w-52 break-all font-mono text-xs font-semibold">{row.bar_code}</span>,
    },
    {
      key: "serial",
      header: language === "ar" ? "الرقم الخارجي" : "External No.",
      cell: row => <span className="block max-w-44 break-all font-mono text-xs">{row.serial_number ?? "-"}</span>,
    },
    {
      key: "purity",
      header: language === "ar" ? "العيار" : "Purity",
      cell: row => <span>{row.purity_name ?? "-"}</span>,
    },
    {
      key: "weight",
      header: language === "ar" ? "الوزن" : "Weight",
      cell: row => <span className="font-mono">{fmtGrams(Number(row.weight_grams ?? row.weight))} g</span>,
    },
    {
      key: "location",
      header: language === "ar" ? "الموقع" : "Location",
      cell: row => <div className="text-xs"><div className="font-medium">{row.vault_name ?? "-"}</div><div className="text-muted-foreground">{row.branch_name ?? "-"}</div></div>,
    },
    {
      key: "inventory",
      header: language === "ar" ? "المخزون" : "Inventory",
      cell: row => <span className="font-mono text-xs">{row.current_inventory ?? "-"}</span>,
    },
    {
      key: "owner",
      header: language === "ar" ? "المالك" : "Owner",
      cell: row => <span>{row.current_owner_type === "platform" ? (language === "ar" ? "المنصة" : "Platform") : (language === "ar" ? "عميل" : "Customer")}</span>,
    },
    {
      key: "cost",
      header: language === "ar" ? "التكلفة" : "Cost",
      cell: row => <span className="font-mono">{row.total_cost ? Number(row.total_cost).toLocaleString() : "-"}</span>,
    },
    {
      key: "status",
      header: language === "ar" ? "الحالة" : "Status",
      cell: row => <StatusBadge tone={barStatusTone[row.status] ?? "neutral"}>{statusText[row.status]?.[language] ?? row.status}</StatusBadge>,
    },
    {
      key: "reserved",
      header: language === "ar" ? "الحجز" : "Reserved",
      cell: row => <span className="text-xs">{row.is_reserved ? (language === "ar" ? "محجوزة" : "Yes") : "-"}</span>,
    },
    {
      key: "lastMovement",
      header: language === "ar" ? "آخر حركة" : "Last movement",
      cell: row => <div className="text-xs"><div>{row.last_movement_type ?? "-"}</div><div className="text-muted-foreground">{row.last_movement_at ? formatDateTime(row.last_movement_at) : "-"}</div></div>,
    },
    {
      key: "actions",
      header: language === "ar" ? "الإجراء" : "Action",
      align: "end",
      cell: row => (
        <Button size="sm" variant="outline" onClick={e => { e.stopPropagation(); router.push(`/bullion-bars/${row.id}`) }}>
          <Eye className="h-3.5 w-3.5" />
          {language === "ar" ? "عرض" : "View"}
        </Button>
      ),
    },
  ]

  const available = bars.filter(b => b.status === "available").length
  const reserved = bars.filter(b => b.status === "reserved").length
  const blocked = bars.filter(b => b.status === "blocked").length

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "سجل السبيكات" : "Bullion Registry"}
        description={language === "ar" ? "السجل الرئيسي لكل سبيكة ذهب." : "Master record for each gold bar."}
        breadcrumbs={[
          { label: language === "ar" ? "المخزون واللوجستيات" : "Inventory & Logistics", href: "#" },
          { label: language === "ar" ? "سجل السبيكات" : "Bullion Registry" },
        ]}
        actions={
          <Button variant="outline" onClick={refresh} disabled={isLoading}>
            <RefreshCw className="h-4 w-4" />
          </Button>
        }
      />

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label={language === "ar" ? "إجمالي السبيكات" : "Total bars"} value={String(bars.length)} icon={Key} tone="gold" accent />
        <KpiCard label={language === "ar" ? "متاحة" : "Available"} value={String(available)} icon={CheckCircle2} tone="success" />
        <KpiCard label={language === "ar" ? "محجوزة" : "Reserved"} value={String(reserved)} icon={AlertOctagon} tone="warning" />
        <KpiCard label={language === "ar" ? "مجمّدة" : "Blocked"} value={String(blocked)} icon={Snowflake} tone="danger" />
      </div>

      <SectionCard title={language === "ar" ? "البحث والتصفية" : "Search and filters"}>
        <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_220px_180px]">
        <label className="relative">
          <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
          <input
            className="w-full rounded-lg border border-border bg-background py-2.5 pl-9 pr-3 text-sm"
            placeholder={language === "ar" ? "البحث بالباركود أو الرقم التسلسلي" : "Search by bar code or serial"}
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </label>
        <select className="h-10 rounded-md border border-border bg-background px-3 text-sm" value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
          {registryStatuses.map(status => <option key={status || "all"} value={status}>{status ? (statusText[status]?.[language] ?? status) : (language === "ar" ? "كل الحالات" : "All statuses")}</option>)}
        </select>
        <select className="h-10 rounded-md border border-border bg-background px-3 text-sm" value={ownerFilter} onChange={e => setOwnerFilter(e.target.value)}>
          <option value="">{language === "ar" ? "كل الملاك" : "All owners"}</option>
          <option value="platform">{language === "ar" ? "المنصة" : "Platform"}</option>
          <option value="customer">{language === "ar" ? "العملاء" : "Customers"}</option>
        </select>
        </div>
      </SectionCard>

      <SectionCard title={language === "ar" ? "قائمة السبيكات" : "Bars"} padded={false}>
        {error && <div className="m-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">{error}</div>}
        {isLoading ? (
          <div className="flex h-52 items-center justify-center">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
          </div>
        ) : (
          <DataTable
            columns={columns}
            data={filtered}
            rowKey={row => row.id}
            onRowClick={row => router.push(`/bullion-bars/${row.id}`)}
            ariaLabel="Bullion bars"
            empty={<div className="text-center text-sm text-muted-foreground">{language === "ar" ? "لا توجد سبيكات." : "No bars."}</div>}
          />
        )}
      </SectionCard>
    </div>
  )
}
