'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useParams } from "next/navigation"
import { Calculator, CheckCircle2, Pencil, Plus, Printer, RefreshCw, Trash2, XCircle } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { api } from "@/lib/api"
import { useAuth } from "@/contexts/auth-context"
import { sellErrorMessage, useSellOrders } from "@/hooks/useSellOrders"
import { allowedSellActions, displayCustomer, sellStatusLabel, sellStatusTone, type SellAction } from "@/lib/sell-orders"
import type { BranchDTO, PaginatedResponse, PuritySummary, SellOrderItem, SellOrderItemPayload, VaultDTO } from "@/types"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { StatusBadge } from "@/components/ui/status-badge"
import { Button } from "@/components/ui/button"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField, TextAreaField } from "@/components/ui/FormFields"
import { fmtGrams, fmtMoney, formatDateTime } from "@/lib/format"

type OrderForm = { priority: string; branch_id: string; vault_id: string; notes: string }

const actionLabels: Record<SellAction, { en: string; ar: string }> = {
  submit: { en: "Submit for review", ar: "إرسال للمراجعة" },
  review: { en: "Submit for approval", ar: "إرسال للاعتماد" },
  approve: { en: "Approve", ar: "اعتماد" },
  reject: { en: "Reject", ar: "رفض" },
  cancel: { en: "Cancel", ar: "إلغاء" },
  post: { en: "Post", ar: "ترحيل" },
  delivering: { en: "Mark delivering", ar: "بدء التسليم" },
  delivered: { en: "Mark delivered", ar: "تم التسليم" },
  close: { en: "Close", ar: "إغلاق" },
  reverse: { en: "Reverse posting", ar: "عكس الترحيل" },
}

const blankItem = (): SellOrderItemPayload => ({
  purity_id: "",
  weight_grams: 0,
  quantity: 1,
  price_per_gram: 0,
  premium: 0,
  notes: "",
})

function arrayPayload<T>(value: any): T[] {
  const payload = value?.data ?? value
  return Array.isArray(payload) ? payload : (payload as PaginatedResponse<T>)?.items ?? []
}

export default function SellOrderDetailPage() {
  const { id } = useParams<{ id: string }>()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { user } = useAuth()
  const {
    selected: order,
    support,
    isLoading,
    isSubmitting,
    error,
    get,
    loadSupport,
    act,
    update,
    addItem,
    updateItem,
    deleteItem,
    recalculate,
    quote,
  } = useSellOrders()
  const [purities, setPurities] = useState<PuritySummary[]>([])
  const [branches, setBranches] = useState<BranchDTO[]>([])
  const [vaults, setVaults] = useState<VaultDTO[]>([])
  const [action, setAction] = useState<SellAction | null>(null)
  const [reason, setReason] = useState("")
  const [itemOpen, setItemOpen] = useState(false)
  const [editing, setEditing] = useState<SellOrderItem | null>(null)
  const [item, setItem] = useState<SellOrderItemPayload>(blankItem())
  const [itemBusy, setItemBusy] = useState(false)
  const [orderEditOpen, setOrderEditOpen] = useState(false)
  const [orderForm, setOrderForm] = useState<OrderForm>({ priority: "normal", branch_id: "", vault_id: "", notes: "" })

  const refresh = useCallback(async () => {
    await get(id)
    await loadSupport(id)
  }, [get, id, loadSupport])

  useEffect(() => {
    refresh()
    Promise.all([
      api.get("/purities/", { params: { active_only: true } }),
      api.get("/branches/"),
      api.get("/warehouse/vaults"),
    ])
      .then(([p, b, v]) => {
        setPurities(arrayPayload<PuritySummary>(p))
        setBranches(arrayPayload<BranchDTO>(b))
        setVaults(arrayPayload<VaultDTO>(v))
      })
      .catch(() => undefined)
  }, [refresh])

  const actions = useMemo(() => order ? allowedSellActions(order.status, user?.permissions ?? []) : [], [order, user?.permissions])
  const needsReason = action === "reject" || action === "cancel" || action === "reverse"
  const canEditDraft = order?.status === "draft" && user?.permissions?.includes("sell_orders:update")
  const selectedVaults = vaults.filter(vault => !orderForm.branch_id || vault.branch_id === orderForm.branch_id)

  const runAction = async () => {
    if (!action || !order) return
    if (needsReason && !reason.trim()) return toast.error(language === "ar" ? "السبب مطلوب." : "Reason is required.")
    if (action === "approve" && !support.availability?.is_available) {
      return toast.error(language === "ar" ? "لا يمكن الاعتماد قبل نجاح التحقق من الرصيد والتوفر." : "Approval requires a successful availability check.")
    }
    try {
      await act(order.id, action, reason.trim() || undefined)
      toast.success(language === "ar" ? "تم تنفيذ الإجراء." : "Action completed.")
      setAction(null)
      setReason("")
      await refresh()
    } catch (err) {
      toast.error(sellErrorMessage(err))
    }
  }

  const openOrderEdit = () => {
    if (!order) return
    setOrderForm({
      priority: order.priority || "normal",
      branch_id: order.branch_id || "",
      vault_id: order.vault_id || "",
      notes: order.notes || "",
    })
    setOrderEditOpen(true)
  }

  const saveOrderEdit = async () => {
    if (!order) return
    if (!orderForm.branch_id || !orderForm.vault_id) return toast.error(language === "ar" ? "اختر الفرع والخزنة." : "Select branch and vault.")
    try {
      await update(order.id, { ...orderForm, priority: orderForm.priority as "low" | "normal" | "high" | "urgent" })
      toast.success(language === "ar" ? "تم تحديث بيانات الأمر." : "Order details updated.")
      setOrderEditOpen(false)
      await refresh()
    } catch (err) {
      toast.error(sellErrorMessage(err))
    }
  }

  const openItem = (current?: SellOrderItem) => {
    setEditing(current ?? null)
    setItem(current ? {
      purity_id: current.purity_id ?? "",
      weight_grams: Number(current.weight_grams),
      quantity: current.quantity,
      price_per_gram: Number(current.price_per_gram),
      premium: Number(current.premium),
      notes: current.notes,
    } : blankItem())
    setItemOpen(true)
  }

  const saveItem = async () => {
    if (!order) return
    if (!order.currency_id) return toast.error(language === "ar" ? "لا توجد عملة مرتبطة بالأمر." : "Order currency is missing.")
    if (!item.purity_id || Number(item.weight_grams) <= 0 || Number(item.quantity || 0) <= 0) {
      return toast.error(language === "ar" ? "العيار والوزن والكمية مطلوبة." : "Purity, weight, and quantity are required.")
    }
    setItemBusy(true)
    try {
      const price = await quote(item.purity_id, order.currency_id)
      const payload = { ...item, price_per_gram: Number(price.sell_price_per_gram) }
      if (editing) await updateItem(order.id, editing.id, payload)
      else await addItem(order.id, payload)
      setItemOpen(false)
      await refresh()
      toast.success(language === "ar" ? "تم حفظ البند." : "Item saved.")
    } catch (err) {
      toast.error(sellErrorMessage(err))
    } finally {
      setItemBusy(false)
    }
  }

  const removeItem = async (itemId: string) => {
    if (!order || !confirm(language === "ar" ? "حذف هذا البند؟" : "Delete this item?")) return
    try {
      await deleteItem(order.id, itemId)
      await refresh()
      toast.success(language === "ar" ? "تم حذف البند." : "Item deleted.")
    } catch (err) {
      toast.error(sellErrorMessage(err))
    }
  }

  const recalc = async () => {
    if (!order) return
    try {
      await recalculate(order.id)
      await refresh()
      toast.success(language === "ar" ? "تم تحديث التسعير." : "Pricing refreshed.")
    } catch (err) {
      toast.error(sellErrorMessage(err))
    }
  }

  if (isLoading && !order) {
    return <div className="flex h-80 items-center justify-center"><div className="h-9 w-9 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" /></div>
  }

  if (!order) {
    return <div className="rounded-lg border border-red-200 bg-red-50 p-6 text-red-700">{error || "Sell order not found"}</div>
  }

  const currency = order.currency?.code ?? undefined

  return (
    <div className="space-y-6">
      <PageHeader
        title={order.sell_order_no}
        description={displayCustomer(order.customer, language)}
        breadcrumbs={[
          { label: language === "ar" ? "أوامر البيع" : "Sell orders", href: "/sell-orders" },
          { label: order.sell_order_no },
        ]}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={refresh} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
            </Button>
            {canEditDraft && (
              <Button variant="outline" onClick={openOrderEdit}>
                <Pencil className="h-4 w-4" />
                {language === "ar" ? "تعديل" : "Edit"}
              </Button>
            )}
            {support.voucher && (
              <Button variant="outline" onClick={() => window.print()}>
                <Printer className="h-4 w-4" />
                {language === "ar" ? "طباعة السند" : "Print voucher"}
              </Button>
            )}
          </div>
        }
      />
      {error && <div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">{error}</div>}

      <div className="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">
        <SectionCard title={language === "ar" ? "ملخص أمر البيع" : "Sell order summary"}>
          <div className="mb-5 flex items-center justify-between">
            <StatusBadge tone={sellStatusTone[order.status]}>{sellStatusLabel[order.status][language]}</StatusBadge>
            <span className="text-xs text-muted-foreground">{formatDateTime(order.created_at)}</span>
          </div>
          <div className="grid gap-3 sm:grid-cols-2">
            <Row label={language === "ar" ? "العميل" : "Customer"} value={displayCustomer(order.customer, language)} />
            <Row label={language === "ar" ? "الفرع" : "Branch"} value={(language === "ar" ? order.branch?.name_ar : order.branch?.name_en) || "-"} />
            <Row label={language === "ar" ? "الخزنة" : "Vault"} value={order.vault?.name || "-"} />
            <Row label={language === "ar" ? "العملة" : "Currency"} value={currency || "-"} />
            <Row label={language === "ar" ? "الأولوية" : "Priority"} value={order.priority} />
            <Row label={language === "ar" ? "منشئ الأمر" : "Created by"} value={order.created_by?.full_name || order.created_by?.email || "-"} />
          </div>
          {order.notes && <p className="mt-4 rounded-lg bg-muted/40 p-3 text-sm text-muted-foreground">{order.notes}</p>}
        </SectionCard>

        <SectionCard title={language === "ar" ? "ملخص التسعير" : "Pricing breakdown"}>
          <div className="space-y-3">
            <MoneyRow label={language === "ar" ? "قيمة الذهب" : "Gold value"} value={order.subtotal_amount} currency={currency} />
            <MoneyRow label={language === "ar" ? "الرسوم" : "Fees"} value={order.fee_amount} currency={currency} />
            <MoneyRow label={language === "ar" ? "الضريبة" : "Tax"} value={order.tax_amount} currency={currency} />
            <MoneyRow label={language === "ar" ? "الخصم" : "Discount"} value={order.discount_amount} currency={currency} />
            <div className="border-t border-border pt-3">
              <MoneyRow label={language === "ar" ? "الإجمالي النهائي" : "Final amount"} value={order.total_amount} currency={currency} strong />
            </div>
          </div>
          {order.expires_at && <p className="mt-4 text-xs text-muted-foreground">{language === "ar" ? "صلاحية السعر: " : "Price expires: "}{formatDateTime(order.expires_at)}</p>}
          {order.price_snapshot && (
            <div className="mt-4 rounded-lg border border-border bg-muted/30 p-3">
              <p className="mb-2 text-xs font-semibold text-muted-foreground">{language === "ar" ? "لقطة السعر" : "Price snapshot"}</p>
              <pre className="max-h-32 overflow-auto whitespace-pre-wrap text-[11px] text-muted-foreground">{JSON.stringify(order.price_snapshot, null, 2)}</pre>
            </div>
          )}
          {order.status === "draft" && (
            <Button className="mt-4 w-full" variant="outline" onClick={recalc}>
              <Calculator className="h-4 w-4" />
              {language === "ar" ? "إعادة احتساب السعر" : "Recalculate pricing"}
            </Button>
          )}
        </SectionCard>
      </div>

      <SectionCard title={language === "ar" ? "بنود الذهب" : "Gold items"} padded={false}>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-muted/50 text-left text-xs text-muted-foreground">
              <tr>
                <th className="p-3">{language === "ar" ? "العيار" : "Purity"}</th>
                <th className="p-3">{language === "ar" ? "الوزن" : "Weight"}</th>
                <th className="p-3">{language === "ar" ? "السعر" : "Price/g"}</th>
                <th className="p-3">{language === "ar" ? "الإجمالي" : "Total"}</th>
                {order.status === "draft" && <th className="p-3" />}
              </tr>
            </thead>
            <tbody>
              {order.items.map(current => (
                <tr key={current.id} className="border-t border-border">
                  <td className="p-3 font-semibold">{current.purity?.karat}K {language === "ar" ? current.purity?.name_ar : current.purity?.name_en}</td>
                  <td className="p-3 font-mono">{fmtGrams(Number(current.weight_grams) * current.quantity)}</td>
                  <td className="p-3 font-mono">{fmtMoney(Number(current.price_per_gram), currency)}</td>
                  <td className="p-3 font-mono font-semibold">{fmtMoney(Number(current.line_total), currency)}</td>
                  {order.status === "draft" && (
                    <td className="p-3">
                      <div className="flex justify-end gap-1">
                        <Button size="sm" variant="ghost" onClick={() => openItem(current)}><Pencil className="h-4 w-4" /></Button>
                        <Button size="sm" variant="ghost" onClick={() => removeItem(current.id)}><Trash2 className="h-4 w-4 text-red-600" /></Button>
                      </div>
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {order.status === "draft" && (
          <div className="border-t border-border p-3">
            <Button size="sm" variant="outline" onClick={() => openItem()}>
              <Plus className="h-4 w-4" />
              {language === "ar" ? "إضافة بند" : "Add item"}
            </Button>
          </div>
        )}
      </SectionCard>

      <div className="grid gap-6 lg:grid-cols-2">
        <SectionCard title={language === "ar" ? "التحقق من الرصيد والتوفر" : "Availability check"}>
          {support.availability ? (
            <div className="space-y-3">
              <div className={`rounded-lg border p-3 ${support.availability.is_available ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-red-200 bg-red-50 text-red-800"}`}>
                <div className="flex items-center gap-2">
                  {support.availability.is_available ? <CheckCircle2 className="h-5 w-5" /> : <XCircle className="h-5 w-5" />}
                  <strong>{support.availability.is_available ? (language === "ar" ? "العملية متاحة" : "Order is available") : (language === "ar" ? "العملية غير متاحة" : "Order is blocked")}</strong>
                </div>
              </div>
              {support.availability.customer_cash && (
                <div className="grid grid-cols-3 gap-2 text-center">
                  <Metric label={language === "ar" ? "الرصيد" : "Cash balance"} value={fmtMoney(Number(support.availability.customer_cash.available_before), support.availability.customer_cash.currency_code ?? undefined)} />
                  <Metric label={language === "ar" ? "المطلوب" : "Required"} value={fmtMoney(Number(support.availability.customer_cash.required_amount), support.availability.customer_cash.currency_code ?? undefined)} />
                  <Metric label={language === "ar" ? "بعد العملية" : "After"} value={fmtMoney(Number(support.availability.customer_cash.available_after), support.availability.customer_cash.currency_code ?? undefined)} />
                </div>
              )}
              {support.availability.inventory.map((entry, index) => (
                <div key={entry.pool_id || index} className="rounded-lg border border-border p-3">
                  <p className="font-medium">{entry.purity_name}</p>
                  <p className="text-xs text-muted-foreground">
                    {language === "ar" ? "متاح" : "Available"} {fmtGrams(Number(entry.available_grams))} / {language === "ar" ? "مطلوب" : "Required"} {fmtGrams(Number(entry.required_grams))}
                  </p>
                </div>
              ))}
              {support.availability.blocking_reasons.map(reasonText => <p key={reasonText} className="text-sm text-red-700">{reasonText}</p>)}
            </div>
          ) : (
            <p className="text-sm text-muted-foreground">{language === "ar" ? "يتوفر التحقق بعد تثبيت السعر." : "Availability is shown after the price is locked."}</p>
          )}
        </SectionCard>

        <SectionCard title={language === "ar" ? "إجراءات سير العمل" : "Workflow actions"}>
          <div className="grid gap-2 sm:grid-cols-2">
            {actions.length ? actions.map(value => (
              <Button
                key={value}
                variant={["reject", "cancel", "reverse"].includes(value) ? "danger" : "primary"}
                disabled={value === "approve" && !support.availability?.is_available}
                onClick={() => setAction(value)}
              >
                {actionLabels[value][language]}
              </Button>
            )) : (
              <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد إجراءات متاحة لحسابك في هذه الحالة." : "No actions are available for your account in this state."}</p>
            )}
          </div>
        </SectionCard>
      </div>

      <div className="grid gap-6 xl:grid-cols-2">
        <SectionCard title={language === "ar" ? "سجل الحالات والاعتمادات" : "Status and approvals"}>
          <div className="space-y-3">
            {support.history.map(entry => (
              <Timeline key={entry.id} title={sellStatusLabel[entry.new_status as keyof typeof sellStatusLabel]?.[language] ?? entry.new_status} meta={`${formatDateTime(entry.changed_at)} · ${entry.changed_by_user?.full_name || entry.changed_by_user?.email || "-"}`} note={entry.note} />
            ))}
            {support.approvals.flatMap(request => request.steps).map(step => (
              <Timeline key={step.id} title={`${language === "ar" ? "خطوة اعتماد" : "Approval step"} ${step.step_order}: ${step.status}`} meta={step.decided_at ? formatDateTime(step.decided_at) : "-"} note={step.decision_note} />
            ))}
            {!support.history.length && !support.approvals.length && <p className="text-sm text-muted-foreground">{language === "ar" ? "لا يوجد سجل بعد." : "No status history yet."}</p>}
          </div>
        </SectionCard>

        <SectionCard title={language === "ar" ? "حركات المحفظة والمخزون" : "Wallet and inventory movements"}>
          <div className="space-y-3">
            {support.walletMovements.map(movement => (
              <div key={movement.ledger_entry_id} className="rounded-lg border border-border p-3">
                <div className="flex justify-between">
                  <strong>{movement.wallet_type} · {movement.entry_type}</strong>
                  <span className="font-mono">{movement.amount ? fmtMoney(Number(movement.amount), movement.currency_code ?? undefined) : fmtGrams(Number(movement.grams))}</span>
                </div>
                <p className="text-xs text-muted-foreground">{movement.balance_before ?? "-"} → {movement.balance_after ?? "-"}</p>
              </div>
            ))}
            {support.inventoryMovements.map(movement => (
              <div key={movement.id} className="rounded-lg border border-border p-3">
                <div className="flex justify-between">
                  <strong>{movement.movement_type}</strong>
                  <span className="font-mono">{fmtGrams(Number(movement.quantity))}</span>
                </div>
                <p className="text-xs text-muted-foreground">{movement.reason}</p>
              </div>
            ))}
            {!support.walletMovements.length && !support.inventoryMovements.length && <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد حركات بعد." : "No movements yet."}</p>}
          </div>
        </SectionCard>
      </div>

      <SectionCard title={language === "ar" ? "القيود المحاسبية" : "Accounting journals"}>
        {support.journals.length ? (
          <div className="space-y-4">
            {support.journals.map(journal => (
              <div key={journal.id} className="rounded-lg border border-border">
                <div className="flex justify-between bg-muted/40 p-3">
                  <strong>{journal.journal_number}</strong>
                  <StatusBadge tone={journal.status === "posted" ? "success" : "neutral"}>{journal.status}</StatusBadge>
                </div>
                <div className="divide-y divide-border">
                  {journal.lines.map(line => (
                    <div key={line.id} className="grid grid-cols-[1fr_auto_auto] gap-3 p-3 text-sm">
                      <span>{line.account_code} · {line.account_name}</span>
                      <span className="uppercase text-muted-foreground">{line.entry_type}</span>
                      <span className="font-mono">{fmtMoney(Number(line.amount), currency)}</span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد قيود بعد." : "No journals yet."}</p>
        )}
      </SectionCard>

      <div className="grid gap-6 xl:grid-cols-2">
        <SectionCard title={language === "ar" ? "سجل التدقيق" : "Audit log"}>
          <div className="space-y-2">
            {support.auditLogs.map((log: any) => <Timeline key={log.id} title={log.action} meta={formatDateTime(log.created_at)} note={log.new_values ? JSON.stringify(log.new_values) : undefined} />)}
            {!support.auditLogs.length && <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد سجلات." : "No audit records."}</p>}
          </div>
        </SectionCard>

        <SectionCard title={language === "ar" ? "معاينة سند البيع" : "Sell voucher preview"}>
          {support.voucher ? (
            <div className="space-y-3 rounded-lg border-2 border-gold-300 p-5">
              <div className="flex justify-between">
                <div>
                  <p className="text-xs uppercase text-muted-foreground">Gold Wallet</p>
                  <h3 className="text-lg font-bold">{language === "ar" ? "سند بيع ذهب" : "Gold Sell Voucher"}</h3>
                </div>
                <strong className="font-mono">{support.voucher.order_no}</strong>
              </div>
              <Row label={language === "ar" ? "العميل" : "Customer"} value={displayCustomer(support.voucher.customer, language)} />
              <Row label={language === "ar" ? "الحالة" : "Status"} value={sellStatusLabel[order.status][language]} />
              <MoneyRow label={language === "ar" ? "الإجمالي" : "Total"} value={support.voucher.total_amount} currency={support.voucher.currency?.code} strong />
              <Button variant="outline" className="w-full" onClick={() => window.print()}>
                <Printer className="h-4 w-4" />
                {language === "ar" ? "طباعة" : "Print"}
              </Button>
            </div>
          ) : (
            <p className="text-sm text-muted-foreground">{language === "ar" ? "السند غير متاح بعد." : "Voucher is not available yet."}</p>
          )}
        </SectionCard>
      </div>

      <Modal open={Boolean(action)} onClose={() => setAction(null)} title={action ? actionLabels[action][language] : ""} description={order.sell_order_no} size="sm">
        <div className="space-y-4">
          {action === "approve" && (
            <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">
              {language === "ar" ? "سيتم اعتماد السعر والرصيد وحجز المخزون نهائيا." : "This confirms pricing, balance, and inventory reservation."}
            </div>
          )}
          <TextAreaField
            id="action-reason"
            name="reason"
            label={needsReason ? (language === "ar" ? "السبب" : "Reason") : (language === "ar" ? "ملاحظة" : "Note")}
            required={needsReason}
            value={reason}
            onChange={event => setReason(event.target.value)}
          />
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setAction(null)}>{language === "ar" ? "إغلاق" : "Close"}</Button>
            <Button variant={action && ["reject", "cancel", "reverse"].includes(action) ? "danger" : "primary"} onClick={runAction} isLoading={isSubmitting}>
              {language === "ar" ? "تأكيد" : "Confirm"}
            </Button>
          </div>
        </div>
      </Modal>

      <Modal open={orderEditOpen} onClose={() => setOrderEditOpen(false)} title={language === "ar" ? "تعديل بيانات الأمر" : "Edit order information"} size="md">
        <div className="grid gap-4 sm:grid-cols-2">
          <SelectField id="edit-priority" name="priority" label={language === "ar" ? "الأولوية" : "Priority"} value={orderForm.priority} onChange={event => setOrderForm(current => ({ ...current, priority: event.target.value }))} options={["low", "normal", "high", "urgent"].map(value => ({ value, label: value }))} />
          <SelectField id="edit-branch" name="branch_id" label={language === "ar" ? "الفرع" : "Branch"} required value={orderForm.branch_id} onChange={event => setOrderForm(current => ({ ...current, branch_id: event.target.value, vault_id: "" }))} options={branches.filter(branch => branch.status === "active").map(branch => ({ value: branch.id, label: language === "ar" ? branch.name_ar : branch.name_en || branch.name_ar }))} />
          <SelectField id="edit-vault" name="vault_id" label={language === "ar" ? "الخزنة" : "Vault"} required value={orderForm.vault_id} onChange={event => setOrderForm(current => ({ ...current, vault_id: event.target.value }))} options={selectedVaults.map(vault => ({ value: vault.id, label: vault.name }))} />
          <div className="sm:col-span-2">
            <TextAreaField id="edit-notes" name="notes" label={language === "ar" ? "ملاحظات" : "Notes"} value={orderForm.notes} onChange={event => setOrderForm(current => ({ ...current, notes: event.target.value }))} />
          </div>
        </div>
        <div className="mt-4 flex justify-end gap-2">
          <Button variant="outline" onClick={() => setOrderEditOpen(false)}>{language === "ar" ? "إلغاء" : "Cancel"}</Button>
          <Button onClick={saveOrderEdit} isLoading={isSubmitting}>{language === "ar" ? "حفظ" : "Save"}</Button>
        </div>
      </Modal>

      <Modal open={itemOpen} onClose={() => setItemOpen(false)} title={editing ? (language === "ar" ? "تعديل البند" : "Edit item") : (language === "ar" ? "إضافة بند" : "Add item")} size="md">
        <div className="grid gap-4 sm:grid-cols-2">
          <SelectField id="item-purity" name="purity_id" label={language === "ar" ? "العيار" : "Purity"} required value={item.purity_id} onChange={event => setItem(value => ({ ...value, purity_id: event.target.value }))} options={purities.map(purity => ({ value: purity.id, label: `${purity.karat}K - ${language === "ar" ? purity.name_ar : purity.name_en}` }))} />
          <InputField id="item-weight" name="weight_grams" label={language === "ar" ? "الوزن" : "Weight"} type="number" min="0.000001" step="0.000001" value={item.weight_grams} onChange={event => setItem(value => ({ ...value, weight_grams: Number(event.target.value) }))} />
          <InputField id="item-qty" name="quantity" label={language === "ar" ? "الكمية" : "Quantity"} type="number" min="1" value={item.quantity ?? 1} onChange={event => setItem(value => ({ ...value, quantity: Number(event.target.value) }))} />
          <InputField id="item-premium" name="premium" label={language === "ar" ? "العلاوة" : "Premium"} type="number" min="0" value={item.premium ?? 0} onChange={event => setItem(value => ({ ...value, premium: Number(event.target.value) }))} />
        </div>
        <div className="mt-4 flex justify-end gap-2">
          <Button variant="outline" onClick={() => setItemOpen(false)}>{language === "ar" ? "إلغاء" : "Cancel"}</Button>
          <Button onClick={saveItem} isLoading={itemBusy}>{language === "ar" ? "حفظ" : "Save"}</Button>
        </div>
      </Modal>
    </div>
  )
}

function Row({ label, value }: { label: string; value: string }) {
  return <div className="flex justify-between gap-3 text-sm"><span className="text-muted-foreground">{label}</span><span className="text-right font-medium">{value}</span></div>
}

function MoneyRow({ label, value, currency, strong }: { label: string; value: string | number; currency?: string | null; strong?: boolean }) {
  return <div className="flex justify-between"><span className="text-sm text-muted-foreground">{label}</span><span className={`font-mono ${strong ? "text-lg font-bold" : "font-semibold"}`}>{fmtMoney(Number(value), currency ?? undefined)}</span></div>
}

function Metric({ label, value }: { label: string; value: string }) {
  return <div className="rounded-lg bg-muted/40 p-2"><p className="text-[10px] uppercase text-muted-foreground">{label}</p><p className="mt-1 font-mono text-xs font-bold">{value}</p></div>
}

function Timeline({ title, meta, note }: { title: string; meta: string; note?: string | null }) {
  return <div className="border-l-2 border-gold-300 pl-3"><div className="flex justify-between gap-3"><strong className="text-sm">{title}</strong><span className="text-[11px] text-muted-foreground">{meta}</span></div>{note && <p className="mt-1 break-words text-xs text-muted-foreground">{note}</p>}</div>
}
