'use client'

import { FormEvent, useEffect, useMemo, useState } from "react"
import type { ReactNode } from "react"
import {
  AlertTriangle,
  Ban,
  CheckCircle2,
  ClipboardCheck,
  FileCheck,
  FileText,
  History,
  Loader2,
  PackageOpen,
  PlusCircle,
  Printer,
  RotateCcw,
  Scale,
  Search,
  Send,
  ShieldCheck,
  XCircle,
} from "lucide-react"
import { useSearchParams } from "next/navigation"
import { toast } from "sonner"
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 { Modal } from "@/components/ui/modal"
import { Button } from "@/components/ui/button"
import { InputField, SelectField, TextAreaField } from "@/components/ui/FormFields"
import { SearchableSelectField, type SearchableSelectOption } from "@/components/ui/searchable-select-field"
import { useReceivingOrders } from "@/hooks/useReceiving"
import { useBranches } from "@/hooks/useBranches"
import { useVaults } from "@/hooks/useVaults"
import { useCustomers } from "@/hooks/useCustomers"
import { useSuppliers } from "@/hooks/useSuppliers"
import { usePurities } from "@/hooks/usePurities"
import { useAuth } from "@/contexts/auth-context"
import type {
  AssayResultCreatePayload,
  ReceivingOrderCreatePayload,
  ReceivingOrderItemCreatePayload,
  ReceivingOrderRead,
  ReceivingOrderWorkflowAction,
  ReceivingReceiptRead,
} from "@/types"
import { formatDateTime, formatNumber } from "@/lib/format"
import i18n from "@/lib/i18n"

const t = (key: string, options?: Record<string, unknown>) => i18n.t(`app.admin.warehouse.receiving.requests.${key}`, options)

const statusTone: Record<string, StatusTone> = {
  pending: "pending",
  under_review: "warning",
  inspected: "info",
  approved: "info",
  received: "processing",
  posted: "success",
  rejected: "danger",
  cancelled: "neutral",
}

const actionLabels: Record<ReceivingOrderWorkflowAction, string> = {
  "submit-for-review": t("action.submit"),
  approve: t("action.approve"),
  reject: t("action.reject"),
  "mark-received": t("action.mark_received"),
  post: t("action.post"),
  cancel: t("action.cancel"),
  resubmit: t("action.resubmit"),
}

const actionIcons: Record<ReceivingOrderWorkflowAction, typeof Send> = {
  "submit-for-review": Send,
  approve: ShieldCheck,
  reject: XCircle,
  "mark-received": CheckCircle2,
  post: FileCheck,
  cancel: Ban,
  resubmit: RotateCcw,
}

type CreateForm = {
  order_type: "customer" | "supplier"
  priority: string
  customer_id: string
  supplier_id: string
  branch_id: string
  vault_id: string
  purity_id: string
  declared_weight_grams: number | ""
  price_per_gram: number | ""
  premium: number | ""
  quantity: number | ""
  condition_grade: string
  notes: string
}

type AssayForm = {
  item_id: string
  method: string
  purity_id: string
  final_weight_grams: number | ""
  net_gold_grams: number | ""
  result: string
  grade: string
  remarks: string
}

const initialCreate: CreateForm = {
  order_type: "customer",
  priority: "normal",
  customer_id: "",
  supplier_id: "",
  branch_id: "",
  vault_id: "",
  purity_id: "",
  declared_weight_grams: "",
  price_per_gram: "",
  premium: "",
  quantity: 1,
  condition_grade: "",
  notes: "",
}

const initialAssay: AssayForm = {
  item_id: "",
  method: "manual",
  purity_id: "",
  final_weight_grams: "",
  net_gold_grams: "",
  result: "accepted",
  grade: "A",
  remarks: "",
}

function shortId(value?: string | null) {
  return value ? value.slice(0, 8) : "-"
}

function weight(value?: string | number | null) {
  if (value === undefined || value === null || value === "") return "-"
  return `${formatNumber(Number(value))} ${t("unit.grams")}`
}

function money(value?: string | number | null) {
  if (value === undefined || value === null || value === "") return "-"
  return formatNumber(Number(value))
}

function statusLabel(value: string) {
  return t(`status.${value}`)
}

function Status({ value }: { value: string }) {
  return <StatusBadge tone={statusTone[value] || "neutral"}>{statusLabel(value)}</StatusBadge>
}

function useReceivingAccess() {
  const { user } = useAuth()
  const set = new Set(user?.permissions || [])
  const roles = new Set(user?.roles?.map((role) => role.code) || [])
  const manager = roles.has("super_admin") || roles.has("warehouse_manager") || roles.has("finance_admin")
  return {
    canCreate: manager || set.has("receiving_order:create"),
    canUpdate: manager || set.has("receiving_order:update") || set.has("receiving_order:review"),
    canInspect: manager || set.has("receiving_order:inspect"),
    canApprove: manager || set.has("receiving_order:approve"),
    canReceive: manager || set.has("receiving_order:receive"),
    canPost: manager || set.has("receiving_order:post"),
    canCancel: manager || set.has("receiving_order:cancel"),
  }
}

function availableActions(order: ReceivingOrderRead, access: ReturnType<typeof useReceivingAccess>): ReceivingOrderWorkflowAction[] {
  switch (order.status) {
    case "pending":
      return [
        ...(access.canUpdate ? ["submit-for-review" as const] : []),
        ...(access.canCancel ? ["cancel" as const] : []),
      ]
    case "under_review":
      return [
        ...(access.canReceive ? ["mark-received" as const] : []),
        ...(access.canApprove ? ["reject" as const] : []),
        ...(access.canCancel ? ["cancel" as const] : []),
      ]
    case "received":
      return [
        ...(access.canCancel ? ["cancel" as const] : []),
      ]
    case "inspected":
      return [
        ...(access.canApprove ? ["approve" as const, "reject" as const] : []),
        ...(access.canCancel ? ["cancel" as const] : []),
      ]
    case "approved":
      return [
        ...(access.canPost ? ["post" as const] : []),
        ...(access.canCancel ? ["cancel" as const] : []),
      ]
    case "rejected":
      return access.canCreate ? ["resubmit"] : []
    default:
      return []
  }
}

function actionNeedsReason(action: ReceivingOrderWorkflowAction | null) {
  return action === "reject" || action === "cancel"
}

function toCreatePayload(form: CreateForm): ReceivingOrderCreatePayload {
  const item: ReceivingOrderItemCreatePayload = {
    purity_id: form.purity_id || null,
    declared_weight_grams: Number(form.declared_weight_grams || 0),
    price_per_gram: Number(form.price_per_gram || 0),
    cost_per_gram: Number(form.price_per_gram || 0),
    premium: Number(form.premium || 0),
    quantity: Number(form.quantity || 1),
    condition_grade: form.condition_grade || null,
  }
  return {
    order_type: form.order_type,
    priority: form.priority,
    customer_id: form.order_type === "customer" ? form.customer_id || null : null,
    supplier_id: form.order_type === "supplier" ? form.supplier_id || null : null,
    branch_id: form.branch_id || null,
    vault_id: form.vault_id || null,
    purity_id: form.purity_id || null,
    estimated_weight_grams: Number(form.declared_weight_grams || 0),
    condition_grade: form.condition_grade || null,
    notes: form.notes || null,
    items: [item],
  }
}

function option(value: string, label: string, description?: string | null): SearchableSelectOption {
  return { value, label, description: description || undefined }
}

type DisplayRecord = Record<string, unknown>

function recordValue(record: unknown, keys: string[]) {
  if (!record || typeof record !== "object") return ""
  const source = record as DisplayRecord
  for (const key of keys) {
    const value = source[key]
    if (typeof value === "string" && value.trim()) return value
    if (typeof value === "number") return String(value)
  }
  return ""
}

function relatedRecord(record: unknown, keys: string[]) {
  if (!record || typeof record !== "object") return null
  const source = record as DisplayRecord
  for (const key of keys) {
    const value = source[key]
    if (value && typeof value === "object") return value
  }
  return null
}

function customerDisplay(record: unknown) {
  return recordValue(record, ["name", "full_name_ar", "full_name_en", "customer_name", "customer_code", "phone", "email"])
}

function supplierDisplay(record: unknown) {
  return recordValue(record, ["name", "name_ar", "name_en", "supplier_name", "supplier_no", "code"])
}

function purityDisplay(record: unknown) {
  const name = recordValue(record, ["name", "name_ar", "name_en", "purity_name", "karat"])
  return name && /^\d+$/.test(name) ? `${name}K` : name
}

function toAssayPayload(form: AssayForm, itemDeclaredWeight?: string | null): AssayResultCreatePayload {
  const finalWeight = Number(form.final_weight_grams || 0)
  const declaredWeight = Number(itemDeclaredWeight || 0)
  return {
    method: form.method || null,
    purity_id: form.purity_id || null,
    final_weight_grams: finalWeight,
    net_gold_grams: Number(form.net_gold_grams || finalWeight),
    difference_grams: finalWeight && declaredWeight ? finalWeight - declaredWeight : null,
    result: form.result,
    grade: form.grade || null,
    remarks: form.remarks || null,
    notes: form.remarks || null,
  }
}

function printReceipt(
  receipt: ReceivingReceiptRead | null,
  labels: {
    customer: (record: unknown, id?: string | null) => string
    supplier: (record: unknown, id?: string | null) => string
    branch: (id?: string | null) => string
    vault: (id?: string | null) => string
    purity: (record: unknown, id?: string | null) => string
  },
) {
  if (!receipt) return
  const win = window.open("", "_blank", "width=900,height=1100")
  if (!win) {
    toast.error(t("toast.popup_blocked"))
    return
  }
  const rows = receipt.items.map((item) => `
    <tr>
      <td>${labels.purity(item, item.purity_id)}</td>
      <td>${weight(item.declared_weight_grams)}</td>
      <td>${weight(item.accepted_weight_grams || item.measured_weight_grams)}</td>
      <td>${item.condition_grade || "-"}</td>
    </tr>
  `).join("")
  win.document.write(`
    <html>
      <head>
        <title>${t("receipt.title")} ${receipt.order_no}</title>
        <style>
          body { font-family: Arial, sans-serif; padding: 32px; color: #111827; }
          .top { display: flex; justify-content: space-between; border-bottom: 2px solid #d6a51d; padding-bottom: 16px; margin-bottom: 24px; }
          .brand { font-size: 13px; font-weight: 700; color: #a97900; text-transform: uppercase; letter-spacing: .08em; }
          h1 { margin: 6px 0 0; font-size: 26px; }
          table { width: 100%; border-collapse: collapse; margin-top: 18px; }
          td, th { border: 1px solid #d1d5db; padding: 10px; font-size: 13px; text-align: left; }
          th { background: #f9fafb; }
          .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 24px; }
          .sig { margin-top: 56px; display: flex; gap: 80px; }
          .line { border-top: 1px solid #111827; padding-top: 8px; min-width: 160px; text-align: center; }
          button { margin-bottom: 20px; padding: 8px 12px; }
        </style>
      </head>
      <body>
        <button onclick="window.print()">${t("action.print")}</button>
        <div class="top">
          <div><div class="brand">Gold Wallet</div><h1>${t("receipt.title")}</h1></div>
          <div><strong>${t("field.request_no")}:</strong> ${receipt.order_no}<br/><strong>${t("field.status")}:</strong> ${statusLabel(receipt.status)}</div>
        </div>
        <div class="grid">
          <div><strong>${t("field.customer")}:</strong> ${labels.customer(receipt, receipt.customer_id)}</div>
          <div><strong>${t("field.supplier")}:</strong> ${labels.supplier(receipt, receipt.supplier_id)}</div>
          <div><strong>${t("field.branch")}:</strong> ${labels.branch(receipt.branch_id)}</div>
          <div><strong>${t("field.vault")}:</strong> ${labels.vault(receipt.vault_id)}</div>
          <div><strong>${t("field.received_at")}:</strong> ${receipt.received_at || "-"}</div>
          <div><strong>${t("field.posted_at")}:</strong> ${receipt.posted_at || "-"}</div>
        </div>
        <table>
          <thead><tr><th>${t("field.purity")}</th><th>${t("field.expected_weight")}</th><th>${t("field.final_weight")}</th><th>${t("field.grade")}</th></tr></thead>
          <tbody>${rows}</tbody>
        </table>
        <div class="sig">
          <div class="line">${t("signature.receiver")}</div>
          <div class="line">${t("signature.inspector")}</div>
          <div class="line">${t("signature.manager")}</div>
        </div>
      </body>
    </html>
  `)
  win.document.close()
  win.focus()
}

export default function ReceivingPage() {
  const receiving = useReceivingOrders()
  const { items: branches, fetchItems: fetchBranches } = useBranches()
  const { items: vaults, fetchItems: fetchVaults } = useVaults()
  const customers = useCustomers()
  const suppliers = useSuppliers()
  const purities = usePurities()
  const access = useReceivingAccess()
  const searchParams = useSearchParams()
  const requestedOrderId = searchParams.get("order")

  const [selected, setSelected] = useState<ReceivingOrderRead | null>(null)
  const [createOpen, setCreateOpen] = useState(false)
  const [actionOpen, setActionOpen] = useState(false)
  const [assayOpen, setAssayOpen] = useState(false)
  const [selectedAction, setSelectedAction] = useState<ReceivingOrderWorkflowAction | null>(null)
  const [actionNote, setActionNote] = useState("")
  const [statusFilter, setStatusFilter] = useState("")
  const [customerFilter, setCustomerFilter] = useState("")
  const [supplierFilter, setSupplierFilter] = useState("")
  const [branchFilter, setBranchFilter] = useState("")
  const [createForm, setCreateForm] = useState<CreateForm>(initialCreate)
  const [assayForm, setAssayForm] = useState<AssayForm>(initialAssay)

  const reload = () => receiving.fetchItems(1, 100, "", {
    status: statusFilter,
    customer_id: customerFilter,
    supplier_id: supplierFilter,
    branch_id: branchFilter,
  })

  useEffect(() => {
    receiving.fetchItems(1, 100)
    fetchBranches(1, 100)
    fetchVaults(1, 100)
    customers.fetchItems(1, 100, "", { status: "active" })
    suppliers.fetchItems(1, 100, "", { status: "approved" })
    purities.fetchItems(1, 100, "", { is_active: true })
  }, [fetchBranches, fetchVaults, receiving.fetchItems, customers.fetchItems, suppliers.fetchItems, purities.fetchItems])

  useEffect(() => {
    if (!selected) return
    receiving.fetchStatusHistory(selected.id)
    receiving.fetchPostingPreview(selected.id)
    receiving.fetchReceipt(selected.id)
  }, [selected?.id])

  useEffect(() => {
    if (!requestedOrderId || selected?.id === requestedOrderId) return
    const requestedOrder = receiving.items.find((row) => row.id === requestedOrderId)
    if (requestedOrder) setSelected(requestedOrder)
  }, [receiving.items, requestedOrderId, selected?.id])

  const selectedFresh = selected ? receiving.items.find((row) => row.id === selected.id) || selected : null
  const selectedItems = selectedFresh?.items || []

  const getCustomerName = (id?: string | null, source?: unknown) => {
    const embedded = customerDisplay(source) || customerDisplay(relatedRecord(source, ["customer", "customer_profile", "party"]))
    if (embedded) return embedded
    if (!id) return "-"
    const c = customers.items.find((x) => x.id === id)
    return c ? (customerDisplay(c) || shortId(c.id)) : shortId(id)
  }

  const getSupplierName = (id?: string | null, source?: unknown) => {
    const embedded = supplierDisplay(source) || supplierDisplay(relatedRecord(source, ["supplier", "party"]))
    if (embedded) return embedded
    if (!id) return "-"
    const s = suppliers.items.find((x) => x.id === id)
    return s ? (supplierDisplay(s) || shortId(s.id)) : shortId(id)
  }

  const getPurityName = (id?: string | null, source?: unknown) => {
    const embedded = purityDisplay(source) || purityDisplay(relatedRecord(source, ["purity", "measured_purity"]))
    if (embedded) return embedded
    if (!id) return "-"
    const p = purities.items.find((x) => x.id === id)
    return p ? (purityDisplay(p) || `${p.karat}K`) : shortId(id)
  }

  const getBranchName = (id?: string | null) => {
    if (!id) return "-"
    const branch = branches.find((row) => row.id === id)
    return branch ? (branch.name_ar || branch.name_en || branch.code || shortId(branch.id)) : shortId(id)
  }

  const getVaultName = (id?: string | null) => {
    if (!id) return "-"
    const vault = vaults.find((row) => row.id === id)
    return vault ? (vault.name || vault.code || shortId(vault.id)) : shortId(id)
  }

  const translateSystemText = (text: string | null | undefined): string => {
    if (!text) return ""
    if (text.includes("Order created")) return t("notes.order_created")
    if (text.includes("Order must be approved before posting")) return t("warnings.must_be_approved")
    if (text.includes("Order must be received before posting")) return t("warnings.must_be_received")
    if (text.includes("gold_inventory_receipt")) return t("journal_types.gold_inventory_receipt")
    return text
  }

  const customerOptions = customers.items
    .filter((customer) => customer.status === "active")
    .map((customer) => option(customer.id, customerDisplay(customer) || shortId(customer.id), [customer.customer_code, customer.phone, customer.email].filter(Boolean).join(" | ")))
  const supplierOptions = suppliers.items.map((supplier) => option(supplier.id, supplierDisplay(supplier) || shortId(supplier.id), [supplier.supplier_no, supplier.supplier_type].filter(Boolean).join(" | ")))
  const branchOptions = branches.map((branch) => option(branch.id, branch.name_ar || branch.name_en || branch.code, branch.code))
  const vaultOptions = vaults
    .filter((vault) => !createForm.branch_id || vault.branch_id === createForm.branch_id)
    .map((vault) => option(vault.id, vault.name || vault.code, vault.code))
  const filterVaultOptions = vaults.map((vault) => option(vault.id, vault.name || vault.code, vault.code))
  const purityOptions = purities.items.map((purity) => option(purity.id, purityDisplay(purity) || `${purity.karat}K`, `${purity.karat}K | ${purity.purity_ratio}`))

  const stats = useMemo(() => {
    return receiving.items.reduce(
      (acc, row) => {
        acc.total += 1
        if (row.status === "inspected") acc.needsApproval += 1
        if (row.status === "approved") acc.readyToPost += 1
        if (row.status === "posted") acc.posted += 1
        return acc
      },
      { total: 0, needsApproval: 0, readyToPost: 0, posted: 0 },
    )
  }, [receiving.items])

  const createRequest = async (event: FormEvent) => {
    event.preventDefault()
    if (createForm.order_type === "customer" && !createForm.customer_id) {
      toast.error(t("validation.customer_required"))
      return
    }
    if (createForm.order_type === "supplier" && !createForm.supplier_id) {
      toast.error(t("validation.supplier_required"))
      return
    }
    if (!createForm.purity_id || Number(createForm.declared_weight_grams) <= 0) {
      toast.error(t("validation.gold_required"))
      return
    }
    if (Number(createForm.price_per_gram) <= 0) {
      toast.error(t("validation.price_required"))
      return
    }
    const order = await receiving.createOrder(toCreatePayload(createForm))
    if (!order) return
    toast.success(t("toast.created"))
    setCreateOpen(false)
    setCreateForm(initialCreate)
    setSelected(order)
  }

  const openAction = (order: ReceivingOrderRead, action: ReceivingOrderWorkflowAction) => {
    setSelected(order)
    setSelectedAction(action)
    setActionNote("")
    setActionOpen(true)
  }

  const runAction = async () => {
    if (!selectedFresh || !selectedAction) return
    if (actionNeedsReason(selectedAction) && !actionNote.trim()) {
      toast.error(t("validation.reason_required"))
      return
    }
    const ok = await receiving.transitionOrder(selectedFresh.id, selectedAction, actionNote.trim() || undefined)
    if (!ok) return
    toast.success(t("toast.action_done", { action: actionLabels[selectedAction] }))
    setActionOpen(false)
    setSelectedAction(null)
    setActionNote("")
    await reload()
  }

  const openAssay = (order: ReceivingOrderRead) => {
    const firstItem = order.items?.find((item) => !item.assay_result_id) || order.items?.[0]
    setSelected(order)
    setAssayForm({
      ...initialAssay,
      item_id: firstItem?.id || "",
      purity_id: firstItem?.purity_id || order.purity_id || "",
      final_weight_grams: firstItem?.accepted_weight_grams ? Number(firstItem.accepted_weight_grams) : "",
      net_gold_grams: firstItem?.accepted_weight_grams ? Number(firstItem.accepted_weight_grams) : "",
    })
    setAssayOpen(true)
  }

  const saveAssay = async (event: FormEvent) => {
    event.preventDefault()
    if (!selectedFresh || !assayForm.item_id || Number(assayForm.final_weight_grams) <= 0) {
      toast.error(t("validation.inspection_required"))
      return
    }
    const item = selectedItems.find((row) => row.id === assayForm.item_id)
    const ok = await receiving.addAssayResult(selectedFresh.id, assayForm.item_id, toAssayPayload(assayForm, item?.declared_weight_grams))
    if (!ok) return
    toast.success(t("toast.inspection_saved"))
    setAssayOpen(false)
    await reload()
  }

  const columns: Column<ReceivingOrderRead>[] = [
    {
      key: "request",
      header: t("field.request_no"),
      cell: (row) => <button className="font-mono text-xs font-semibold hover:text-gold-700" onClick={() => setSelected(row)}>{row.receiving_order_no}</button>,
    },
    {
      key: "party",
      header: t("field.party"),
      cell: (row) => {
        let name = "-"
        if (row.order_type === "customer") name = getCustomerName(row.customer_id, row)
        else if (row.order_type === "supplier") name = getSupplierName(row.supplier_id, row)
        else name = customerDisplay(row) || supplierDisplay(row) || shortId(row.user_id)
        return <span className="text-sm font-medium">{name}</span>
      },
    },
    {
      key: "type",
      header: t("field.type"),
      cell: (row) => t(`type.${row.order_type}`),
    },
    {
      key: "weight",
      header: t("field.weight"),
      cell: (row) => weight(row.actual_weight_grams || row.estimated_weight_grams),
    },
    {
      key: "diff",
      header: t("field.difference"),
      cell: (row) => {
        const diff = Number(row.weight_difference || 0)
        return <span className={diff === 0 ? "font-mono text-muted-foreground" : diff > 0 ? "font-mono text-emerald-700" : "font-mono text-red-700"}>{weight(row.weight_difference)}</span>
      },
    },
    {
      key: "status",
      header: t("field.status"),
      cell: (row) => <Status value={row.status} />,
    },
    {
      key: "created",
      header: t("field.created_at"),
      cell: (row) => <span className="text-xs text-muted-foreground">{formatDateTime(row.created_at)}</span>,
    },
    {
      key: "actions",
      header: t("field.actions"),
      align: "end",
      cell: (row) => {
        const actions = availableActions(row, access)
        return (
          <div className="flex flex-wrap justify-end gap-1" onClick={(event) => event.stopPropagation()}>
            {access.canInspect && row.status === "received" && (
              <Button size="sm" variant="outline" onClick={() => openAssay(row)}>
                <Scale className="h-3.5 w-3.5" />{t("action.transfer_to_inspection")}
              </Button>
            )}
            {actions.map((action) => {
              const Icon = actionIcons[action]
              return (
                <Button key={action} size="sm" variant={action === "reject" || action === "cancel" ? "outline" : "primary"} onClick={() => openAction(row, action)}>
                  <Icon className="h-3.5 w-3.5" />
                  {actionLabels[action]}
                </Button>
              )
            })}
          </div>
        )
      },
    },
  ]

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <PageHeader
          title={t("title")}
          description={t("description")}
          breadcrumbs={[{ label: t("warehouse"), href: "#" }, { label: t("title") }]}
        />
        {access.canCreate && (
          <Button onClick={() => setCreateOpen(true)}>
            <PlusCircle className="h-4 w-4" />
            {t("action.create")}
          </Button>
        )}
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard label={t("kpi.total")} value={String(stats.total)} icon={PackageOpen} tone="gold" />
        <KpiCard label={t("kpi.needs_approval")} value={String(stats.needsApproval)} icon={ShieldCheck} tone="warning" />
        <KpiCard label={t("kpi.ready_to_post")} value={String(stats.readyToPost)} icon={FileCheck} tone="info" />
        <KpiCard label={t("status.posted")} value={String(stats.posted)} icon={CheckCircle2} tone="success" />
      </div>

      <SectionCard title={t("section.filters")}>
        <div className="grid gap-3 md:grid-cols-4">
          <SelectField
            id="status_filter"
            name="status_filter"
            label={t("field.status")}
            value={statusFilter}
            onChange={(event) => setStatusFilter(event.target.value)}
            options={["pending", "under_review", "received", "inspected", "approved", "posted", "rejected", "cancelled"].map((value) => ({ value, label: statusLabel(value) }))}
          />
          <SearchableSelectField
            id="customer_filter"
            label={t("field.customer")}
            value={customerFilter}
            onChange={setCustomerFilter}
            options={customerOptions}
            placeholder={t("placeholder.search_customer")}
          />
          <SearchableSelectField
            id="supplier_filter"
            label={t("field.supplier")}
            value={supplierFilter}
            onChange={setSupplierFilter}
            options={supplierOptions}
            placeholder={t("placeholder.search_supplier")}
          />
          <SearchableSelectField
            id="branch_filter"
            label={t("field.branch")}
            value={branchFilter}
            onChange={setBranchFilter}
            options={branchOptions}
            placeholder={t("placeholder.search_branch")}
          />
          <div className="flex items-end gap-2">
            <Button type="button" onClick={reload}><Search className="h-4 w-4" />{t("action.apply_filters")}</Button>
            <Button type="button" variant="outline" onClick={() => { setStatusFilter(""); setCustomerFilter(""); setSupplierFilter(""); setBranchFilter(""); receiving.fetchItems(1, 100) }}>{t("action.clear")}</Button>
          </div>
        </div>
      </SectionCard>

      <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_420px]">
        <SectionCard title={t("section.requests")} padded={false}>
          {receiving.isLoading ? (
            <div className="flex h-48 items-center justify-center"><Loader2 className="h-7 w-7 animate-spin" /></div>
          ) : (
            <DataTable columns={columns} data={receiving.items} rowKey={(row) => row.id} activeRowKey={selectedFresh?.id} onRowClick={(row) => setSelected(row)} ariaLabel={t("section.requests")} />
          )}
        </SectionCard>

        <SectionCard title={selectedFresh ? selectedFresh.receiving_order_no : t("section.details")}>
          {!selectedFresh ? (
            <p className="py-8 text-center text-sm text-muted-foreground">{t("empty.select_request")}</p>
          ) : (
            <div className="space-y-5">
              <div className="grid gap-3 sm:grid-cols-2">
                <Info label={t("field.status")} value={<Status value={selectedFresh.status} />} />
                <Info label={t("field.type")} value={t(`type.${selectedFresh.order_type}`)} />
                <Info label={t("field.customer")} value={getCustomerName(selectedFresh.customer_id, selectedFresh)} />
                <Info label={t("field.supplier")} value={getSupplierName(selectedFresh.supplier_id, selectedFresh)} />
                <Info label={t("field.expected_weight")} value={weight(selectedFresh.estimated_weight_grams)} />
                <Info label={t("field.final_weight")} value={weight(selectedFresh.actual_weight_grams)} />
                <Info label={t("field.difference")} value={weight(selectedFresh.weight_difference)} />
                <Info label={t("field.total_amount")} value={money(selectedFresh.total_amount)} />
              </div>

              <div className="rounded-md border border-border">
                <div className="border-b border-border bg-muted/30 px-3 py-2 text-sm font-semibold">{t("section.inspection")}</div>
                <div className="divide-y divide-border">
                  {selectedItems.length ? selectedItems.map((item) => (
                    <div key={item.id} className="grid grid-cols-4 gap-2 px-3 py-2 text-xs">
                      <span className="text-sm font-medium">{getPurityName(item.purity_id, item)}</span>
                      <span>{weight(item.declared_weight_grams)}</span>
                      <span>{weight(item.accepted_weight_grams || item.measured_weight_grams)}</span>
                      <span>{item.assay_result_id ? t("status.inspected") : t("status.pending_inspection")}</span>
                    </div>
                  )) : <div className="px-3 py-6 text-center text-sm text-muted-foreground">{t("empty.no_items")}</div>}
                </div>
              </div>

              <div className="rounded-md border border-border">
                <div className="border-b border-border bg-muted/30 px-3 py-2 text-sm font-semibold">{t("section.timeline")}</div>
                <div className="space-y-3 p-3">
                  {receiving.statusHistory.length ? receiving.statusHistory.map((row) => (
                    <div key={row.id} className="flex gap-3 text-xs">
                      <History className="mt-0.5 h-3.5 w-3.5 text-gold-600" />
                      <div>
                        <div className="font-semibold">{row.old_status ? `${statusLabel(row.old_status)} -> ` : ""}{statusLabel(row.new_status)}</div>
                        <div className="text-muted-foreground">{formatDateTime(row.changed_at)} {row.note ? `- ${translateSystemText(row.note)}` : ""}</div>
                      </div>
                    </div>
                  )) : <p className="text-sm text-muted-foreground">{t("empty.no_history")}</p>}
                </div>
              </div>

              <div className="rounded-md border border-border">
                <div className="border-b border-border bg-muted/30 px-3 py-2 text-sm font-semibold">{t("section.posting_preview")}</div>
                <div className="space-y-3 p-3 text-xs">
                  {receiving.postingPreview?.warnings?.length ? (
                    <div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-amber-800">
                      <AlertTriangle className="mr-1 inline h-3.5 w-3.5" />
                      {receiving.postingPreview.warnings.map(w => translateSystemText(w)).join(" ")}
                    </div>
                  ) : null}
                  {(receiving.postingPreview?.expected_journals || []).map((entry, index) => (
                    <div key={index} className="rounded-md bg-muted/30 p-2">
                      <div className="font-semibold">{translateSystemText(String(entry.type || "")) || "-"}</div>
                      <div className="text-muted-foreground">{t("field.estimated_value")}: {String(entry.estimated_value || "-")}</div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="flex flex-wrap gap-2">
                {selectedFresh.posting_journal_id && (
                  <Button variant="outline" onClick={() => window.location.assign(`/ledger?journal=${selectedFresh.posting_journal_id}`)}>
                    <FileText className="h-4 w-4" />{t("action.view_journal")}
                  </Button>
                )}
                {(selectedFresh.status === "approved" || selectedFresh.status === "posted") && (
                  <Button
                    variant="outline"
                    onClick={async () => printReceipt(await receiving.fetchReceipt(selectedFresh.id), {
                      customer: (record, id) => getCustomerName(id, record),
                      supplier: (record, id) => getSupplierName(id, record),
                      branch: getBranchName,
                      vault: getVaultName,
                      purity: (record, id) => getPurityName(id, record),
                    })}
                  >
                    <Printer className="h-4 w-4" />{t("action.print")}
                  </Button>
                )}
              </div>
            </div>
          )}
        </SectionCard>
      </div>

      <Modal open={createOpen} onClose={() => setCreateOpen(false)} title={t("create.title")} description={t("create.description")} size="lg">
        <form className="space-y-4" onSubmit={createRequest}>
          <div className="grid gap-4 md:grid-cols-2">
            <SelectField label={t("field.type")} id="order_type" name="order_type" value={createForm.order_type} onChange={(event) => setCreateForm({ ...createForm, order_type: event.target.value as CreateForm["order_type"] })} options={[{ value: "customer", label: t("type.customer") }, { value: "supplier", label: t("type.supplier") }]} />
            <SelectField label={t("field.priority")} id="priority" name="priority" value={createForm.priority} onChange={(event) => setCreateForm({ ...createForm, priority: event.target.value })} options={["low", "normal", "high", "urgent"].map((value) => ({ value, label: t(`priority.${value}`) }))} />
            {createForm.order_type === "customer" ? (
              <SearchableSelectField label={t("field.customer")} id="customer_id" value={createForm.customer_id} onChange={(value) => setCreateForm({ ...createForm, customer_id: value })} options={customerOptions} placeholder={t("placeholder.search_customer")} required />
            ) : (
              <SearchableSelectField label={t("field.supplier")} id="supplier_id" value={createForm.supplier_id} onChange={(value) => setCreateForm({ ...createForm, supplier_id: value })} options={supplierOptions} placeholder={t("placeholder.search_supplier")} required />
            )}
            <SearchableSelectField label={t("field.branch")} id="branch_id" value={createForm.branch_id} onChange={(value) => setCreateForm({ ...createForm, branch_id: value, vault_id: "" })} options={branchOptions} placeholder={t("placeholder.search_branch")} />
            <SearchableSelectField label={t("field.vault")} id="vault_id" value={createForm.vault_id} onChange={(value) => setCreateForm({ ...createForm, vault_id: value })} options={vaultOptions.length ? vaultOptions : filterVaultOptions} placeholder={t("placeholder.search_vault")} />
            <SearchableSelectField label={t("field.purity")} id="purity_id" value={createForm.purity_id} onChange={(value) => setCreateForm({ ...createForm, purity_id: value })} options={purityOptions} placeholder={t("placeholder.search_purity")} required />
            <InputField label={t("field.expected_weight")} id="declared_weight" name="declared_weight" type="number" min="0.01" step="0.01" value={createForm.declared_weight_grams} onChange={(event) => setCreateForm({ ...createForm, declared_weight_grams: event.target.value ? Number(event.target.value) : "" })} required />
            <InputField label={t("field.price_per_gram")} id="price_per_gram" name="price_per_gram" type="number" min="0.01" step="0.01" value={createForm.price_per_gram} onChange={(event) => setCreateForm({ ...createForm, price_per_gram: event.target.value ? Number(event.target.value) : "" })} required />
            <InputField label={t("field.premium")} id="premium" name="premium" type="number" min="0" step="0.01" value={createForm.premium} onChange={(event) => setCreateForm({ ...createForm, premium: event.target.value ? Number(event.target.value) : "" })} />
            <InputField label={t("field.quantity")} id="quantity" name="quantity" type="number" min="1" value={createForm.quantity} onChange={(event) => setCreateForm({ ...createForm, quantity: event.target.value ? Number(event.target.value) : "" })} />
            <InputField label={t("field.grade")} id="condition_grade" name="condition_grade" value={createForm.condition_grade} onChange={(event) => setCreateForm({ ...createForm, condition_grade: event.target.value })} />
          </div>
          <div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">{t("create.balance_warning")}</div>
          <TextAreaField label={t("field.notes")} id="notes" name="notes" value={createForm.notes} onChange={(event) => setCreateForm({ ...createForm, notes: event.target.value })} />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button type="button" variant="outline" onClick={() => setCreateOpen(false)}>{t("action.cancel_dialog")}</Button>
            <Button type="submit" isLoading={receiving.isSubmitting}>{t("action.save_draft")}</Button>
          </div>
        </form>
      </Modal>

      <Modal open={assayOpen} onClose={() => setAssayOpen(false)} title={t("inspection.title")} description={selectedFresh?.receiving_order_no} size="lg">
        <form className="space-y-4" onSubmit={saveAssay}>
          <div className="grid gap-4 md:grid-cols-2">
            <SelectField label={t("field.item")} id="item_id" name="item_id" value={assayForm.item_id} onChange={(event) => setAssayForm({ ...assayForm, item_id: event.target.value })} options={selectedItems.map((item) => ({ value: item.id, label: `${getPurityName(item.purity_id, item)} - ${weight(item.declared_weight_grams)}` }))} required />
            <InputField label={t("field.method")} id="method" name="method" value={assayForm.method} onChange={(event) => setAssayForm({ ...assayForm, method: event.target.value })} />
            <SearchableSelectField label={t("field.measured_purity")} id="assay_purity" value={assayForm.purity_id} onChange={(value) => setAssayForm({ ...assayForm, purity_id: value })} options={purityOptions} placeholder={t("placeholder.search_purity")} />
            <InputField label={t("field.final_weight")} id="final_weight" name="final_weight" type="number" min="0.01" step="0.01" value={assayForm.final_weight_grams} onChange={(event) => setAssayForm({ ...assayForm, final_weight_grams: event.target.value ? Number(event.target.value) : "" })} required />
            <InputField label={t("field.net_gold")} id="net_gold" name="net_gold" type="number" min="0" step="0.01" value={assayForm.net_gold_grams} onChange={(event) => setAssayForm({ ...assayForm, net_gold_grams: event.target.value ? Number(event.target.value) : "" })} />
            <SelectField label={t("field.result")} id="result" name="result" value={assayForm.result} onChange={(event) => setAssayForm({ ...assayForm, result: event.target.value })} options={["accepted", "partial_accepted", "rejected", "damaged", "mismatch"].map((value) => ({ value, label: t(`inspection_result.${value}`) }))} />
            <InputField label={t("field.grade")} id="grade" name="grade" value={assayForm.grade} onChange={(event) => setAssayForm({ ...assayForm, grade: event.target.value })} />
          </div>
          <TextAreaField label={t("field.remarks")} id="remarks" name="remarks" value={assayForm.remarks} onChange={(event) => setAssayForm({ ...assayForm, remarks: event.target.value })} />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button type="button" variant="outline" onClick={() => setAssayOpen(false)}>{t("action.cancel_dialog")}</Button>
            <Button type="submit" isLoading={receiving.isSubmitting}>{t("action.save_inspection")}</Button>
          </div>
        </form>
      </Modal>

      <Modal open={actionOpen} onClose={() => setActionOpen(false)} title={selectedAction ? actionLabels[selectedAction] : t("action.confirm")} description={selectedFresh?.receiving_order_no} size="sm">
        <div className="space-y-4">
          <TextAreaField
            label={actionNeedsReason(selectedAction) ? t("field.reason") : t("field.note")}
            id="action_note"
            name="action_note"
            value={actionNote}
            onChange={(event) => setActionNote(event.target.value)}
            required={actionNeedsReason(selectedAction)}
          />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setActionOpen(false)}>{t("action.cancel_dialog")}</Button>
            <Button variant={selectedAction === "reject" || selectedAction === "cancel" ? "danger" : "primary"} onClick={runAction} isLoading={receiving.isSubmitting}>
              {selectedAction ? actionLabels[selectedAction] : t("action.confirm")}
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

function Info({ label, value }: { label: string; value: ReactNode }) {
  return (
    <div className="rounded-md border border-border bg-muted/20 px-3 py-2">
      <div className="text-[11px] font-medium uppercase text-muted-foreground">{label}</div>
      <div className="mt-1 text-sm font-semibold">{value}</div>
    </div>
  )
}
