'use client'

import { type FormEvent, useCallback, useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import {
  AlertTriangle,
  ArrowDownToLine,
  ArrowRightLeft,
  Boxes,
  CheckCircle2,
  ClipboardCheck,
  ClipboardList,
  Eye,
  FileCheck2,
  FileWarning,
  PackageCheck,
  Plus,

  RefreshCw,
  RotateCcw,
  Send,
  Truck,
  Warehouse,
  XCircle,
} from "lucide-react"
import { useTranslation } from "react-i18next"
import { toast } from "sonner"
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, type StatusTone } from "@/components/ui/status-badge"
import { Button } from "@/components/ui/button"
import { Modal, ModalActions } from "@/components/ui/modal"
import { formatDateTime, formatNumber } from "@/lib/format"

type ModuleKey =
  | "dashboard"
  | "purchaseRequests"
  | "purchaseOrders"
  | "supplierShipments"
  | "inboundPostings"
  | "purchaseReturns"
  | "platformAllocation"
  | "branchAllocation"
  | "outboundOrders"

type Row = Record<string, any>

type EndpointSpec = {
  label: string
  url: string
  params?: Record<string, unknown>
  href?: string
  source: string
}

type ModuleSpec = {
  key: ModuleKey
  icon: typeof Warehouse
  endpoints: EndpointSpec[]
  primaryHref?: string
  createHref?: string
  implementationNote?: { ar: string; en: string }
}

const statusTone: Record<string, StatusTone> = {
  draft: "neutral",
  submitted: "pending",
  pending: "pending",
  pending_review: "warning",
  pending_approval: "warning",
  under_review: "warning",
  approved: "info",
  posted: "success",
  sent_to_supplier: "processing",
  partially_supplied: "processing",
  fully_supplied: "success",
  received: "processing",
  inspected: "info",
  completed: "success",
  converted: "success",
  closed: "success",
  active: "success",
  available: "success",
  reserved: "warning",
  in_transit: "processing",
  pending_pickup: "warning",
  rejected: "danger",
  cancelled: "neutral",
  failed: "danger",
  shortage: "danger",
  critical: "danger",
  danger: "danger",
}

const specs: Record<ModuleKey, ModuleSpec> = {
  dashboard: {
    key: "dashboard",
    icon: Warehouse,
    endpoints: [
      { label: "purchaseRequests", url: "/purchase-requests/", source: "purchase_requests", href: "/warehouse/purchase-requests" },
      { label: "purchaseOrders", url: ENDPOINTS.BUY_ORDERS.LIST, source: "buy_orders", href: "/purchase-orders" },
      { label: "receiving", url: ENDPOINTS.RECEIVING_ORDERS.LIST, source: "receiving_orders", href: "/warehouse/receiving" },
      { label: "bars", url: ENDPOINTS.BARS.LIST, source: "bars", href: "/bullion-bars" },
      { label: "transfers", url: ENDPOINTS.TRANSFERS.LIST, source: "transfer_orders", href: "/warehouse/transfers" },
      { label: "deliveries", url: ENDPOINTS.DELIVERIES.LIST, source: "delivery_orders", href: "/warehouse/deliveries" },
    ],
  },
  purchaseRequests: {
    key: "purchaseRequests",
    icon: ClipboardList,
    endpoints: [{ label: "purchaseRequests", url: ENDPOINTS.PURCHASE_REQUESTS.LIST, source: "purchase_requests" }],
  },
  purchaseOrders: {
    key: "purchaseOrders",
    icon: ArrowDownToLine,
    endpoints: [{ label: "purchaseOrders", url: ENDPOINTS.BUY_ORDERS.LIST, source: "buy_orders", href: "/buy-orders" }],
    primaryHref: "/buy-orders",
    createHref: "/buy-orders/create",
    implementationNote: {
      ar: "هذه الشاشة تعرض أوامر الشراء الحالية من وحدة Buy Orders لأنها هي التطبيق الفعلي لوثيقة Purchase Orders.",
      en: "This screen uses the existing Buy Orders module because it is the implemented Purchase Orders equivalent.",
    },
  },
  supplierShipments: {
    key: "supplierShipments",
    icon: Truck,
    endpoints: [
      { label: "purchaseOrders", url: ENDPOINTS.BUY_ORDERS.LIST, params: { req_status: "sent_to_supplier" }, source: "buy_orders" },
      { label: "receiving", url: ENDPOINTS.RECEIVING_ORDERS.LIST, params: { order_type: "supplier" }, source: "receiving_orders" },
    ],
    primaryHref: "/buy-orders",
    createHref: "/buy-orders/create",
    implementationNote: {
      ar: "لا توجد وحدة Supplier Shipments مستقلة بعد؛ يتم تجميع الشحنات من أوامر الشراء المرسلة للمورد وطلبات استلام الموردين.",
      en: "There is no dedicated Supplier Shipments API yet; this view is composed from supplier purchase orders and supplier receiving orders.",
    },
  },
  inboundPostings: {
    key: "inboundPostings",
    icon: FileCheck2,
    endpoints: [
      { label: "readyToPost", url: ENDPOINTS.RECEIVING_ORDERS.LIST, params: { status: "approved" }, source: "receiving_orders" },
      { label: "posted", url: ENDPOINTS.RECEIVING_ORDERS.LIST, params: { status: "posted" }, source: "receiving_orders" },
    ],
    primaryHref: "/warehouse/receiving",
    implementationNote: {
      ar: "أمر التوريد المخزني مدمج حاليا داخل طلبات الاستلام وليس كوحدة مستقلة.",
      en: "Stock Supply Order is currently integrated in Receiving Orders rather than a separate module.",
    },
  },
  purchaseReturns: {
    key: "purchaseReturns",
    icon: RotateCcw,
    endpoints: [
      { label: "rejectedReceiving", url: ENDPOINTS.RECEIVING_ORDERS.LIST, params: { status: "rejected" }, source: "receiving_orders" },
      { label: "cancelledPurchases", url: ENDPOINTS.BUY_ORDERS.LIST, params: { req_status: "cancelled" }, source: "buy_orders" },
    ],
    primaryHref: "/warehouse/receiving",
    implementationNote: {
      ar: "لا توجد وحدة Purchase Returns مستقلة بعد؛ تعرض الشاشة الرفض والإلغاء المرتبط بسلسلة الشراء والاستلام.",
      en: "There is no dedicated Purchase Returns module yet; this view exposes rejected/cancelled purchase and receiving records.",
    },
  },
  platformAllocation: {
    key: "platformAllocation",
    icon: Boxes,
    endpoints: [
      { label: "fractionalPools", url: ENDPOINTS.INVENTORY.FRACTIONAL_POOLS, source: "fractional_pools" },
      { label: "custody", url: ENDPOINTS.CUSTODY.CHAIN, source: "custody_chain" },
    ],
    primaryHref: "/inventory",
    implementationNote: {
      ar: "تخصيص المنصة يظهر حاليا من المجمعات المشاعة وسلاسل الحيازة؛ لا توجد وحدة Allocation مستقلة بعد.",
      en: "Platform allocation is currently represented by fractional pools and custody chains; a dedicated allocation API is not present yet.",
    },
  },
  branchAllocation: {
    key: "branchAllocation",
    icon: Warehouse,
    endpoints: [
      { label: "vaults", url: ENDPOINTS.INVENTORY.VAULTS, source: "vaults" },
      { label: "transfers", url: ENDPOINTS.TRANSFERS.LIST, source: "transfer_orders" },
    ],
    primaryHref: "/warehouse/transfers",
    implementationNote: {
      ar: "تخصيص الفروع يعتمد حاليا على الخزائن وأوامر النقل بين الفروع.",
      en: "Branch allocation is currently derived from vault balances and transfer orders.",
    },
  },
  outboundOrders: {
    key: "outboundOrders",
    icon: PackageCheck,
    endpoints: [
      { label: "deliveries", url: ENDPOINTS.DELIVERIES.LIST, source: "delivery_orders", href: "/warehouse/deliveries" },
      { label: "transfers", url: ENDPOINTS.TRANSFERS.LIST, source: "transfer_orders", href: "/warehouse/transfers" },
      { label: "sellOrders", url: ENDPOINTS.SELL_ORDERS.LIST, source: "sell_orders", href: "/sell-orders" },
    ],
    primaryHref: "/warehouse/deliveries",
    implementationNote: {
      ar: "لا توجد وحدة أوامر الصرف المخزني مستقلة بعد؛ يتم عرض التسليمات والتحويلات وأوامر البيع كمسار خروج فعلي.",
      en: "There is no dedicated Stock Issue Orders API yet; this view combines deliveries, transfers, and sell orders as the implemented outbound path.",
    },
  },
}

const labels = {
  ar: {
    dashboard: "لوحة المخزون واللوجستيات",
    purchaseRequests: "طلبات الشراء",
    purchaseOrders: "أوامر الشراء",
    supplierShipments: "شحنات الموردين",
    inboundPostings: "أمر التوريد المخزني",
    purchaseReturns: "مرتجعات الشراء",
    platformAllocation: "تخصيص المنصة",
    branchAllocation: "تخصيص الفروع",
    outboundOrders: "أوامر الصرف المخزني",
    description: "متابعة سلسلة المخزون من طلب الشراء حتى الاستلام والفحص والترحيل والتحويل والتسليم.",
    moduleDescription: "عرض تشغيلي متصل بالبيانات المتاحة حاليا مع توضيح الفجوات المتبقية في التنفيذ.",
    warehouse: "المخزون واللوجستيات",
    refresh: "تحديث",
    total: "الإجمالي",
    pending: "قيد الإجراء",
    posted: "مرحلة/مغلقة",
    exceptions: "استثناءات",
    status: "الحالة",
    reference: "المرجع",
    source: "المصدر",
    party: "الطرف",
    weight: "الوزن",
    amount: "القيمة",
    created: "تاريخ الإنشاء",
    linkedPage: "فتح الشاشة الأصلية",
    actions: "الإجراءات",
    open: "فتح",
    create: "إنشاء",
    noRows: "لا توجد بيانات مطابقة.",
    implementationGap: "ملاحظة تنفيذ",
    currentFlow: "المسار الحالي",
    newRequest: "طلب جديد",
    workflow: "مسار طلب الشراء",
    createRequest: "إنشاء طلب شراء",
    submit: "إرسال",
    sendForApproval: "إرسال للاعتماد",
    approve: "اعتماد",
    reject: "رفض",
    convertToPo: "تحويل إلى أمر شراء",
    viewPo: "عرض أمر الشراء",
    cancel: "إلغاء",
  
    noInventoryMovement: "طلب الشراء لا ينشئ أي حركة مخزون.",
  },
  en: {
    dashboard: "Inventory & Logistics Dashboard",
    purchaseRequests: "Purchase Requests",
    purchaseOrders: "Purchase Orders",
    supplierShipments: "Supplier Shipments",
    inboundPostings: "Stock Supply Order",
    purchaseReturns: "Purchase Returns",
    platformAllocation: "Platform Allocation",
    branchAllocation: "Branch Allocation",
    outboundOrders: "Stock Issue Orders",
    description: "Track inventory from purchase request through receiving, inspection, posting, transfers, and delivery.",
    moduleDescription: "Operational view connected to the currently available data, with remaining implementation gaps made visible.",
    warehouse: "Inventory & Logistics",
    refresh: "Refresh",
    total: "Total",
    pending: "Pending action",
    posted: "Posted / closed",
    exceptions: "Exceptions",
    status: "Status",
    reference: "Reference",
    source: "Source",
    party: "Party",
    weight: "Weight",
    amount: "Amount",
    created: "Created",
    linkedPage: "Open source screen",
    actions: "Actions",
    open: "Open",
    create: "Create",
    noRows: "No matching data.",
    implementationGap: "Implementation note",
    currentFlow: "Current flow",
    newRequest: "New request",
    workflow: "Purchase request workflow",
    createRequest: "Create purchase request",
    submit: "Submit",
    sendForApproval: "Send for approval",
    approve: "Approve",
    reject: "Reject",
    convertToPo: "Convert to PO",
    viewPo: "View PO",
    cancel: "Cancel",
   
    noInventoryMovement: "No inventory movement is created by purchase requests.",
  },
}

type PurchaseRequestForm = {
  request_date: string
  metal_type: "gold" | "silver"
  suggested_supplier_id: string
  requested_weight: string
  expected_bar_count: string
  purchase_purpose: string
  target_inventory: string
  justification: string
}

type PendingAction =
  | { type: "submit"; row: Row }
  | { type: "sendForApproval"; row: Row }
  | { type: "approve"; row: Row }
  | { type: "reject"; row: Row; reason: string }
  | { type: "convertToPo"; row: Row; notes: string; supplier_id: string }
  | { type: "cancel"; row: Row; reason: string }

const purchaseRequestSteps = [
  "draft",
  "submitted",
  "pending_approval",
  "approved",
  "converted",
]

const purchasePurposeOptions = [
  "platform_replenishment",
  "branch_stocking",
  "customer_order_fulfillment",
  "coverage_resupply",
  "special_order",
]

const targetInventoryOptions = ["INV_STORE", "INV_PLATFORM", "INV_BRANCH", "INV_INSPECTION"]

const today = () => new Date().toISOString().slice(0, 10)

function createIdempotencyHeaders() {
  return { "Idempotency-Key": (typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).substring(2)) }
}

function initialRequestForm(): PurchaseRequestForm {
  return {
    request_date: today(),
    metal_type: "gold",
    suggested_supplier_id: "",
    requested_weight: "",
    expected_bar_count: "",
    purchase_purpose: "platform_replenishment",
    target_inventory: "INV_STORE",
    justification: "",
  }
}

function unwrapRows(value: unknown): Row[] {
  const payload = value && typeof value === "object" && "data" in value ? (value as any).data : value
  if (Array.isArray(payload)) return payload
  if (payload && typeof payload === "object" && Array.isArray((payload as any).items)) return (payload as any).items
  return []
}

function reference(row: Row) {
  return row.request_no || row.buy_order_no || row.receiving_order_no || row.order_number || row.batch_number || row.bar_code || row.code || row.id || "-"
}

function status(row: Row) {
  return row.status || row.coverage_status || row.inspection_status || "-"
}

function party(row: Row) {
  return row.customer_name || row.supplier_name || row.client_name || row.name || row.name_ar || row.name_en || row.customer_code || row.supplier_no || row.customer_id || row.supplier_id || "-"
}

function supplierOptionLabel(supplier: Row, language: "ar" | "en") {
  const name = (language === "ar" ? supplier.name_ar : supplier.name_en) || supplier.name_ar || supplier.name_en || supplier.supplier_no || supplier.id
  return [name, supplier.supplier_no].filter(Boolean).join(" - ")
}

function weight(row: Row) {
  const value = row.requested_weight ?? row.total_weight ?? row.weight_grams ?? row.weight ?? row.estimated_weight_grams ?? row.actual_weight_grams ?? row.physical_weight ?? row.grams
  return value === undefined || value === null || value === "" ? "-" : `${formatNumber(Number(value))} g`
}

function amount(row: Row) {
  const value = row.total_amount ?? row.subtotal_amount ?? row.current_hold_grams ?? row.available_weight
  return value === undefined || value === null || value === "" ? "-" : formatNumber(Number(value))
}

function created(row: Row) {
  return row.created_at || row.updated_at || row.request_date || row.last_calculated_at || ""
}

function exception(row: Row) {
  const value = status(row)
  return ["rejected", "cancelled", "failed", "shortage", "critical", "danger", "blocked"].includes(String(value))
}

function pending(row: Row) {
  const value = status(row)
  return ["draft", "submitted", "pending", "pending_review", "pending_approval", "under_review", "approved", "sent_to_supplier", "partially_supplied", "received", "inspected", "reserved", "in_transit", "pending_pickup"].includes(String(value))
}

function posted(row: Row) {
  const value = status(row)
  return ["posted", "closed", "completed", "converted", "fully_supplied", "delivered", "active"].includes(String(value))
}

function actionLabel(action: PendingAction["type"], language: "ar" | "en") {
  const en: Record<PendingAction["type"], string> = {
    submit: "Submit draft for review",
    sendForApproval: "Send for approval",
    approve: "Approve request",
    reject: "Reject request",
    convertToPo: "Convert to purchase order",
    cancel: "Cancel request",
  }
  const ar = en
  return language === "ar" ? ar[action] : en[action]
}

function endpointRows(rows: Row[], source: string, href?: string) {
  return rows.map((row) => ({ ...row, _source: source, _href: href }))
}

function rowHref(row: Row) {
  if (!row._href) return ""
  if (row._source === "buy_orders" && row.id) return `/buy-orders/${row.id}`
  if (row._source === "sell_orders" && row.id) return `/sell-orders/${row.id}`
  return row._href
}

export function InventoryLogisticsPage({ moduleKey }: { moduleKey: ModuleKey }) {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const text = labels[language]
  const spec = specs[moduleKey]
  const Icon = spec.icon

  const [rows, setRows] = useState<Row[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [isCreateOpen, setIsCreateOpen] = useState(false)
  const [form, setForm] = useState<PurchaseRequestForm>(() => initialRequestForm())
  const [pendingAction, setPendingAction] = useState<PendingAction | null>(null)
  const [suppliers, setSuppliers] = useState<Row[]>([])

  const load = useCallback(async () => {
    setIsLoading(true)
    setError(null)
    try {
      const responses = await Promise.allSettled(
        spec.endpoints.map((endpoint) => api.get(endpoint.url, { params: { limit: 200, ...endpoint.params } })),
      )
      const next: Row[] = []
      responses.forEach((result, index) => {
        if (result.status === "fulfilled") {
          const endpoint = spec.endpoints[index]
          next.push(...endpointRows(unwrapRows(result.value), endpoint.source, endpoint.href))
        }
      })
      setRows(next)
      const failed = responses.filter((result) => result.status === "rejected").length
      if (failed) setError(language === "ar" ? `تعذر تحميل ${failed} مصدر بيانات.` : `${failed} data source(s) failed to load.`)
    } finally {
      setIsLoading(false)
    }
  }, [language, spec.endpoints])

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

  useEffect(() => {
    if (moduleKey !== "purchaseRequests") return
    api.get(ENDPOINTS.SUPPLIERS.APPROVED, { params: { skip: 0, limit: 500 } })
      .then(response => setSuppliers(unwrapRows(response)))
      .catch(() => setSuppliers([]))
  }, [moduleKey])

  const stats = useMemo(() => ({
    total: rows.length,
    pending: rows.filter(pending).length,
    posted: rows.filter(posted).length,
    exceptions: rows.filter(exception).length,
  }), [rows])

  const updateForm = (key: keyof PurchaseRequestForm, value: string) => {
    setForm((current) => ({ ...current, [key]: value }))
  }

  const createRequest = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    setIsSubmitting(true)
    try {
      await api.post(
        ENDPOINTS.PURCHASE_REQUESTS.CREATE,
        {
          request_date: form.request_date,
          metal_type: form.metal_type,
          suggested_supplier_id: form.suggested_supplier_id || undefined,
          requested_weight: form.requested_weight,
          expected_bar_count: form.expected_bar_count ? Number(form.expected_bar_count) : undefined,
          purchase_purpose: form.purchase_purpose,
          target_inventory: form.target_inventory,
          justification: form.justification || undefined,
        },
        { headers: createIdempotencyHeaders() },
      )
      toast.success(language === "ar" ? "تم إنشاء طلب الشراء كمسودة." : "Purchase request created as draft.")
      setForm(initialRequestForm())
      setIsCreateOpen(false)
      await load()
    } finally {
      setIsSubmitting(false)
    }
  }

  const runAction = async () => {
    if (!pendingAction) return
    setIsSubmitting(true)
    try {
      const id = String(pendingAction.row.id)
      if (pendingAction.type === "submit") {
        await api.post(ENDPOINTS.PURCHASE_REQUESTS.SUBMIT(id), {}, { headers: createIdempotencyHeaders() })
      }
      if (pendingAction.type === "sendForApproval") {
        await api.post(ENDPOINTS.PURCHASE_REQUESTS.SEND_FOR_APPROVAL(id), {}, { headers: createIdempotencyHeaders() })
      }
      if (pendingAction.type === "approve") {
        await api.post(ENDPOINTS.PURCHASE_REQUESTS.APPROVE(id), {}, { headers: createIdempotencyHeaders() })
      }
      if (pendingAction.type === "reject") {
        await api.post(ENDPOINTS.PURCHASE_REQUESTS.REJECT(id), { reason: pendingAction.reason }, { headers: createIdempotencyHeaders() })
      }
      if (pendingAction.type === "convertToPo") {
        const response = await api.post(
          ENDPOINTS.PURCHASE_REQUESTS.CONVERT_TO_PO(id),
          {
            supplier_id: pendingAction.supplier_id || undefined,
            notes: pendingAction.notes || undefined,
          },
          { headers: createIdempotencyHeaders() },
        )
        const buyOrder = response?.data ?? response
        if (buyOrder?.id) {
          toast.success(language === "ar" ? "تم إنشاء أمر الشراء." : "Purchase order created.")
          setPendingAction(null)
          router.push(`/purchase-orders/${buyOrder.id}`)
          return
        }
      }
      if (pendingAction.type === "cancel") {
        await api.post(ENDPOINTS.PURCHASE_REQUESTS.CANCEL(id), { reason: pendingAction.reason || undefined }, { headers: createIdempotencyHeaders() })
      }
      toast.success(language === "ar" ? "تم تحديث طلب الشراء." : "Purchase request updated.")
      setPendingAction(null)
      await load()
    } finally {
      setIsSubmitting(false)
    }
  }

  const requestActions = (row: Row) => {
    const current = String(status(row))
    if (current === "draft") {
      return (
        <>
          <Button size="sm" variant="outline" onClick={() => setPendingAction({ type: "submit", row })}>
            <Send className="h-3.5 w-3.5" />
            {text.submit}
          </Button>
          <Button size="sm" variant="ghost" onClick={() => setPendingAction({ type: "cancel", row, reason: "" })}>
            {text.cancel}
          </Button>
        </>
      )
    }
    if (current === "submitted") {
      return (
        <Button size="sm" variant="outline" onClick={() => setPendingAction({ type: "sendForApproval", row })}>
          <Send className="h-3.5 w-3.5" />
          {text.sendForApproval}
        </Button>
      )
    }
    if (current === "pending_approval") {
      return (
        <>
          <Button size="sm" variant="outline" onClick={() => setPendingAction({ type: "approve", row })}>
            <CheckCircle2 className="h-3.5 w-3.5" />
            {text.approve}
          </Button>
          <Button size="sm" variant="danger" onClick={() => setPendingAction({ type: "reject", row, reason: "" })}>
            <XCircle className="h-3.5 w-3.5" />
            {text.reject}
          </Button>
        </>
      )
    }
    if (current === "approved") {
      return (
        <>
          <Button size="sm" variant="outline" onClick={() => setPendingAction({ type: "convertToPo", row, notes: "", supplier_id: row.suggested_supplier_id || "" })}>
            <ArrowDownToLine className="h-3.5 w-3.5" />
            {text.convertToPo}
          </Button>
          <Button size="sm" variant="ghost" onClick={() => setPendingAction({ type: "cancel", row, reason: "" })}>
            {text.cancel}
          </Button>
        </>
      )
    }
    if (current === "converted" && row.converted_buy_order_id) {
      return (
        <Button size="sm" variant="outline" onClick={() => router.push(`/purchase-orders/${row.converted_buy_order_id}`)}>
          <ArrowDownToLine className="h-3.5 w-3.5" />
          {text.viewPo}
        </Button>
      )
    }
    return <span className="text-xs text-muted-foreground">-</span>
  }

  const columns: Column<Row>[] = [
    {
      key: "reference",
      header: text.reference,
      cell: (row) => <span className="font-mono text-xs font-semibold">{reference(row)}</span>,
    },
    {
      key: "source",
      header: text.source,
      cell: (row) => <span className="text-xs text-muted-foreground">{row._source}</span>,
    },
    {
      key: "party",
      header: text.party,
      cell: (row) => <span>{party(row)}</span>,
    },
    {
      key: "weight",
      header: text.weight,
      cell: (row) => <span className="font-mono text-xs">{weight(row)}</span>,
    },
    {
      key: "amount",
      header: text.amount,
      cell: (row) => <span className="font-mono text-xs">{amount(row)}</span>,
    },
    {
      key: "status",
      header: text.status,
      cell: (row) => <StatusBadge tone={statusTone[String(status(row))] || "neutral"}>{status(row)}</StatusBadge>,
    },
    {
      key: "created",
      header: text.created,
      cell: (row) => <span className="text-xs text-muted-foreground">{created(row) ? formatDateTime(created(row)) : "-"}</span>,
    },
    ...(moduleKey === "purchaseRequests"
      ? [{
          key: "actions",
          header: text.actions,
          cell: (row: Row) => <div className="flex flex-wrap items-center gap-2">{requestActions(row)}</div>,
          className: "min-w-64",
        } satisfies Column<Row>]
      : []),
  ]

  const flow = [
    { href: "/suppliers", label: language === "ar" ? "الموردون" : "Suppliers" },
    { href: "/warehouse/purchase-requests", label: text.purchaseRequests },
    { href: "/purchase-orders", label: text.purchaseOrders },
    { href: "/supplier-shipments", label: text.supplierShipments },
    { href: "/warehouse/receiving", label: language === "ar" ? "الاستلام" : "Receiving" },
    { href: "/warehouse/inspections", label: language === "ar" ? "الفحص" : "Inspections" },
    { href: "/inbound-postings", label: text.inboundPostings },
    { href: "/bullion-bars", label: language === "ar" ? "سجل السبائك" : "Bullion Registry" },
    { href: "/outbound-orders", label: text.outboundOrders },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title={text[moduleKey]}
        description={moduleKey === "dashboard" ? text.description : text.moduleDescription}
        breadcrumbs={[{ label: text.warehouse, href: "/inventory-logistics" }, { label: text[moduleKey] }]}
        actions={
          <div className="flex items-center gap-2">
            {moduleKey === "purchaseRequests" && (
              <Button onClick={() => setIsCreateOpen(true)}>
                <Plus className="h-4 w-4" />
                {text.newRequest}
              </Button>
            )}
            <Button variant="outline" onClick={load} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
              {text.refresh}
            </Button>
          </div>
        }
      />

      {moduleKey === "purchaseRequests" && (
        <SectionCard title={text.workflow} icon={<ClipboardList className="h-4 w-4 text-gold-600" />}>
          <div className="flex flex-wrap items-center gap-2">
            {purchaseRequestSteps.map((step, index) => (
              <div key={step} className="flex items-center gap-2">
                <span className="rounded-md border border-border bg-background px-3 py-2 text-xs font-semibold capitalize">
                  {step === "converted" ? "converted / closed" : step.replaceAll("_", " ")}
                </span>
                {index < purchaseRequestSteps.length - 1 && <ArrowRightLeft className="h-3.5 w-3.5 text-muted-foreground" />}
              </div>
            ))}
          </div>
          <div className="mt-3 rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-xs font-medium text-blue-900">
            {text.noInventoryMovement}
          </div>
        </SectionCard>
      )}

      {moduleKey === "dashboard" && (
        <SectionCard title={text.currentFlow} icon={<Warehouse className="h-4 w-4 text-gold-600" />}>
          <div className="flex flex-wrap items-center gap-2">
            {flow.map((step, index) => (
              <div key={step.href} className="flex items-center gap-2">
                <Link href={step.href} className="rounded-md border border-border bg-background px-3 py-2 text-xs font-semibold hover:border-gold-300 hover:text-gold-700">
                  {step.label}
                </Link>
                {index < flow.length - 1 && <ArrowRightLeft className="h-3.5 w-3.5 text-muted-foreground" />}
              </div>
            ))}
          </div>
        </SectionCard>
      )}

      {spec.implementationNote && (
        <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
          <div className="flex items-start gap-2">
            <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
            <div>
              <div className="font-semibold">{text.implementationGap}</div>
              <p className="mt-0.5">{spec.implementationNote[language]}</p>
            </div>
          </div>
        </div>
      )}

      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <KpiCard label={text.total} value={String(stats.total)} icon={Icon} tone="gold" accent />
        <KpiCard label={text.pending} value={String(stats.pending)} icon={ClipboardCheck} tone="warning" />
        <KpiCard label={text.posted} value={String(stats.posted)} icon={FileCheck2} tone="success" />
        <KpiCard label={text.exceptions} value={String(stats.exceptions)} icon={FileWarning} tone={stats.exceptions ? "danger" : "info"} />
      </div>

      <SectionCard title={text[moduleKey]} padded={false}>
        {error && <div className="m-4 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">{error}</div>}
        {isLoading ? (
          <div className="flex h-48 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={rows}
            rowKey={(row, index) => `${row._source}-${row.id || index}`}
            empty={<div className="text-center text-sm text-muted-foreground">{text.noRows}</div>}
          />
        )}
        {spec.endpoints.some((endpoint) => endpoint.href) && (
          <div className="border-t border-border px-5 py-3 text-xs text-muted-foreground">
            {spec.endpoints.filter((endpoint) => endpoint.href).map((endpoint) => (
              <Link key={`${endpoint.source}-${endpoint.href}`} href={endpoint.href!} className="me-4 font-semibold text-gold-700 hover:underline">
                {text.linkedPage}: {endpoint.source}
              </Link>
            ))}
          </div>
        )}
      </SectionCard>

      <Modal
        open={isCreateOpen}
        onClose={() => setIsCreateOpen(false)}
        title={text.createRequest}
        description={text.noInventoryMovement}
        size="lg"
        footer={
          <ModalActions>
            <Button type="button" variant="outline" onClick={() => setIsCreateOpen(false)}>
              {text.cancel}
            </Button>
            <Button type="submit" form="purchase-request-form" isLoading={isSubmitting}>
              {text.createRequest}
            </Button>
          </ModalActions>
        }
      >
        <form id="purchase-request-form" onSubmit={createRequest} className="grid gap-4 md:grid-cols-2">
          <label className="space-y-1.5 text-sm font-medium">
            Request date
            <input
              type="date"
              required
              value={form.request_date}
              onChange={(event) => updateForm("request_date", event.target.value)}
              className="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
            />
          </label>
          <label className="space-y-1.5 text-sm font-medium">
            Metal
            <select
              value={form.metal_type}
              onChange={(event) => updateForm("metal_type", event.target.value)}
              className="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
            >
              <option value="gold">Gold</option>
              <option value="silver">Silver</option>
            </select>
          </label>
          <label className="space-y-1.5 text-sm font-medium">
            Requested weight, g
            <input
              type="number"
              min="0.000001"
              step="0.000001"
              required
              value={form.requested_weight}
              onChange={(event) => updateForm("requested_weight", event.target.value)}
              className="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
            />
          </label>
          <label className="space-y-1.5 text-sm font-medium">
            Expected bar count
            <input
              type="number"
              min="1"
              value={form.expected_bar_count}
              onChange={(event) => updateForm("expected_bar_count", event.target.value)}
              className="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
            />
          </label>
          <label className="space-y-1.5 text-sm font-medium">
            Purpose
            <select
              value={form.purchase_purpose}
              onChange={(event) => updateForm("purchase_purpose", event.target.value)}
              className="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
            >
              {purchasePurposeOptions.map((option) => (
                <option key={option} value={option}>
                  {option.replaceAll("_", " ")}
                </option>
              ))}
            </select>
          </label>
          <label className="space-y-1.5 text-sm font-medium">
            Target inventory
            <select
              value={form.target_inventory}
              onChange={(event) => updateForm("target_inventory", event.target.value)}
              className="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
            >
              {targetInventoryOptions.map((option) => (
                <option key={option} value={option}>
                  {option}
                </option>
              ))}
            </select>
          </label>
          <label className="space-y-1.5 text-sm font-medium md:col-span-2">
            Suggested supplier
            <select
              value={form.suggested_supplier_id}
              onChange={(event) => updateForm("suggested_supplier_id", event.target.value)}
              className="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
            >
              <option value="">Select after approval / conversion</option>
              {suppliers.map((supplier) => (
                <option key={supplier.id} value={supplier.id}>
                  {supplierOptionLabel(supplier, language)}
                </option>
              ))}
            </select>
          </label>
          <label className="space-y-1.5 text-sm font-medium md:col-span-2">
            Justification
            <textarea
              rows={4}
              value={form.justification}
              onChange={(event) => updateForm("justification", event.target.value)}
              className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
              placeholder="Why is this purchase needed?"
            />
          </label>
        </form>
      </Modal>

      <Modal
        open={Boolean(pendingAction)}
        onClose={() => setPendingAction(null)}
        title={pendingAction ? actionLabel(pendingAction.type, language) : ""}
        description={pendingAction ? `${reference(pendingAction.row)} - ${status(pendingAction.row)}` : undefined}
        size="md"
        footer={
          <ModalActions>
            <Button type="button" variant="outline" onClick={() => setPendingAction(null)}>
              {text.cancel}
            </Button>
            <Button type="button" onClick={runAction} isLoading={isSubmitting}>
              {pendingAction ? actionLabel(pendingAction.type, language) : text.submit}
            </Button>
          </ModalActions>
        }
      >
        <div className="space-y-4">
          <div className="rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-900">
            {text.noInventoryMovement}
          </div>
          {pendingAction?.type === "reject" && (
            <label className="space-y-1.5 text-sm font-medium">
              Rejection reason
              <textarea
                rows={3}
                required
                value={pendingAction.reason}
                onChange={(event) => setPendingAction((current) => current ? ({ ...current, reason: event.target.value } as PendingAction) : current)}
                className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
              />
            </label>
          )}
          {pendingAction?.type === "cancel" && (
            <label className="space-y-1.5 text-sm font-medium">
              Cancel reason
              <textarea
                rows={3}
                value={pendingAction.reason}
                onChange={(event) => setPendingAction((current) => current ? ({ ...current, reason: event.target.value } as PendingAction) : current)}
                className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
              />
            </label>
          )}
          {pendingAction?.type === "convertToPo" && (
            <div className="space-y-4">
              <label className="space-y-1.5 text-sm font-medium">
                Supplier
                <select
                  value={pendingAction.supplier_id}
                  onChange={(event) => setPendingAction((current) => current ? ({ ...current, supplier_id: event.target.value } as PendingAction) : current)}
                  className="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
                >
                  <option value="">No supplier selected</option>
                  {suppliers.map((supplier) => (
                    <option key={supplier.id} value={supplier.id}>
                      {supplierOptionLabel(supplier, language)}
                    </option>
                  ))}
                </select>
              </label>
              <label className="space-y-1.5 text-sm font-medium">
                Conversion notes
                <textarea
                  rows={3}
                  value={pendingAction.notes}
                  onChange={(event) => setPendingAction((current) => current ? ({ ...current, notes: event.target.value } as PendingAction) : current)}
                  className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
                />
              </label>
            </div>
          )}
        </div>
      </Modal>
    </div>
  )
}
