'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useParams, useRouter } from "next/navigation"
import { Calculator, CheckCircle2, Pencil, Printer, RefreshCw } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { useAuth } from "@/contexts/auth-context"
import { usePurchaseOrders } from "@/hooks/usePurchaseOrders"
import {
  ActionBar,
  ActionModal,
  AuditHistory,
  type AuditEntry,
  type DetailTab,
  EntityDetailPage,
  ImpactPreview,
  type WorkflowAction,
} from "@/components/workflow"
import {
  purchaseOrderPermissionMap,
  purchaseOrderStatusLabel,
  purchaseOrderStatusTone,
  purchaseOrderWorkflow,
} from "@/lib/purchase-orders"
import type { AccountingPreview, BranchDTO, CurrencyOption, PurchaseOrder, SupplierDTO } from "@/types"
import { Button } from "@/components/ui/button"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField, TextAreaField } from "@/components/ui/FormFields"
import { fmtMoney, fmtGrams, formatDateTime } from "@/lib/format"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import type { PaginatedResponse } from "@/types"
import { effectivePermissions, hasPermission } from "@/lib/permissions"

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

export default function PurchaseOrderDetailPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const {
    selected: order,
    accountingPreview,
    isLoading,
    isSubmitting,
    error,
    get,
    act,
    getAccountingPreview,
    getStatusHistory,
    recordAdvancePayment,
  } = usePurchaseOrders()

  const [branches, setBranches] = useState<BranchDTO[]>([])
  const [currencies, setCurrencies] = useState<CurrencyOption[]>([])
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [action, setAction] = useState<WorkflowAction | null>(null)
  const [auditLogs, setAuditLogs] = useState<AuditEntry[]>([])
  const [advanceModalOpen, setAdvanceModalOpen] = useState(false)
  const [advanceAmount, setAdvanceAmount] = useState("")
  const [advanceRef, setAdvanceRef] = useState("")
  const [advanceNotes, setAdvanceNotes] = useState("")

  const refresh = useCallback(async () => {
    if (!id) return
    await get(id)
    await getAccountingPreview(id)
    try {
      const rows = await getStatusHistory(id)
      setAuditLogs(rows.map(row => ({
        id: row.id,
        action: row.old_status ? `${row.old_status} -> ${row.new_status}` : row.new_status,
        actor: row.changed_by,
        created_at: row.changed_at,
        new_values: row.note ? { note: row.note } : null,
      })))
    } catch { setAuditLogs([]) }
  }, [id, get, getAccountingPreview, getStatusHistory])

  useEffect(() => {
    refresh()
    Promise.all([
      api.get("/branches/"),
      api.get(ENDPOINTS.CURRENCIES.LIST),
      api.get("/suppliers/"),
    ])
      .then(([b, c, s]) => {
        setBranches(arrayPayload<BranchDTO>(b))
        setCurrencies(Array.isArray(c?.data ?? c) ? (c?.data ?? c) : [])
        setSuppliers(arrayPayload<SupplierDTO>(s))
      })
      .catch(() => undefined)
  }, [refresh])

  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 || "Purchase order not found"}</div>
  }

  const currency = currencies.find(c => c.id === order.currency_id)
  const supplier = suppliers.find(s => s.id === order.supplier_id)
  const supplierName = supplier ? (language === "ar" ? supplier.name_ar : supplier.name_en || supplier.name_ar) : (order.supplier_reference ?? "")
  const branch = branches.find(b => b.id === order.target_branch_id)
  const permissions = effectivePermissions(user)
  const canEditDraft = order.status === "draft" && hasPermission(user, "buy_orders:update")

  const handleAction = async (reason?: string) => {
    if (!action || !order) return
    try {
      await act(order.id, action.key, reason, reason)
      toast.success(language === "ar" ? "تم تنفيذ الإجراء." : "Action completed.")
      setAction(null)
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Action failed")
    }
  }

  const handleAdvancePayment = async () => {
    if (!order || !advanceAmount || Number(advanceAmount) <= 0) return
    try {
      await recordAdvancePayment(order.id, {
        amount: Number(advanceAmount),
        reference: advanceRef || undefined,
        notes: advanceNotes || undefined,
      })
      toast.success(language === "ar" ? "تم تسجيل الدفعة المقدمة." : "Advance payment recorded.")
      setAdvanceModalOpen(false)
      setAdvanceAmount("")
      setAdvanceRef("")
      setAdvanceNotes("")
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to record payment")
    }
  }

  const onActionClick = (a: WorkflowAction) => {
    if (a.key === "create_shipment") {
      router.push(`/supplier-shipments/create?purchase_order_id=${order.id}`)
      return
    }
    if (a.key === "record_advance_payment") {
      setAdvanceModalOpen(true)
      return
    }
    setAction(a)
  }

  const tabs: DetailTab[] = [
    {
      key: "details",
      label: { en: "Order details", ar: "تفاصيل الأمر" },
      content: (
        <div className="grid gap-3 sm:grid-cols-2">
          <Row label={language === "ar" ? "رقم الأمر" : "Order No"} value={order.buy_order_no} />
          <Row label={language === "ar" ? "الأولوية" : "Priority"} value={order.priority} />
          <Row label={language === "ar" ? "الفرع" : "Branch"} value={(language === "ar" ? branch?.name_ar : branch?.name_en) ?? "-"} />
          <Row label={language === "ar" ? "العملة" : "Currency"} value={currency?.code ?? "-"} />
          <Row label={language === "ar" ? "مرجع المورد" : "Supplier Ref"} value={order.supplier_reference ?? "-"} />
          <Row label={language === "ar" ? "مرجع خارجي" : "External Ref"} value={order.external_reference ?? "-"} />
          <Row label={language === "ar" ? "تاريخ التسليم المتوقع" : "Expected Delivery"} value={order.expected_delivery_date ?? "-"} />
          <Row label={language === "ar" ? "الإنشاء" : "Created"} value={formatDateTime(order.created_at)} />
          {order.notes && <div className="sm:col-span-2"><Row label={language === "ar" ? "ملاحظات" : "Notes"} value={order.notes} /></div>}
        </div>
      ),
    },
    {
      key: "supplier",
      label: { en: "Supplier", ar: "المورد" },
      content: (
        <div className="grid gap-3 sm:grid-cols-2">
          <Row label={language === "ar" ? "اسم المورد" : "Supplier Name"} value={supplierName} />
          <Row label={language === "ar" ? "كود المورد" : "Supplier Code"} value={supplier?.supplier_no ?? "-"} />
          <Row label={language === "ar" ? "النوع" : "Type"} value={supplier?.supplier_type ?? "-"} />
          <Row label={language === "ar" ? "الحالة" : "Status"} value={supplier?.status ?? "-"} />
        </div>
      ),
    },
    {
      key: "metals",
      label: { en: "Metals / Items", ar: "المعادن / البنود" },
      badge: order.items.length,
      content: (
        <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" ? "المعدن" : "Metal"}</th>
                <th className="p-3">{language === "ar" ? "الوزن" : "Weight"}</th>
                <th className="p-3">{language === "ar" ? "الكمية" : "Qty"}</th>
                <th className="p-3">{language === "ar" ? "طريقة السعر" : "Price basis"}</th>
                <th className="p-3">{language === "ar" ? "السعر" : "Price"}</th>
                <th className="p-3">{language === "ar" ? "العلاوة" : "Premium"}</th>
                <th className="p-3">{language === "ar" ? "الإجمالي" : "Total"}</th>
              </tr>
            </thead>
            <tbody>
              {order.items.map(item => (
                <tr key={item.id} className="border-t border-border">
                  <td className="p-3 font-semibold capitalize">{item.metal_type}</td>
                  <td className="p-3 font-mono">{fmtGrams(Number(item.weight_grams))}</td>
                  <td className="p-3 font-mono">{item.quantity}</td>
                  <td className="p-3">{item.pricing_basis === "per_unit" ? (language === "ar" ? "لكل وحدة" : "Per unit") : (language === "ar" ? "لكل جرام" : "Per gram")}</td>
                  <td className="p-3 font-mono">{fmtMoney(Number(item.price_per_gram), currency?.code)}</td>
                  <td className="p-3 font-mono">{fmtMoney(Number(item.premium), currency?.code)}</td>
                  <td className="p-3 font-mono font-semibold">{fmtMoney(Number(item.line_total), currency?.code)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ),
    },
    {
      key: "costs",
      label: { en: "Costs", ar: "التكاليف" },
      content: (
        <div className="space-y-3 max-w-md">
          <MoneyRow label={language === "ar" ? "قيمة المعادن" : "Metal value"} value={order.subtotal_amount} currency={currency?.code} />
          <MoneyRow label={language === "ar" ? "الرسوم" : "Fees"} value={order.fee_amount} currency={currency?.code} />
          <MoneyRow label={language === "ar" ? "الضريبة" : "Tax"} value={order.tax_amount} currency={currency?.code} />
          <MoneyRow label={language === "ar" ? "الخصم" : "Discount"} value={order.discount_amount} currency={currency?.code} />
          <div className="border-t border-border pt-3">
            <MoneyRow label={language === "ar" ? "الإجمالي" : "Total"} value={order.total_amount} currency={currency?.code} strong />
          </div>
        </div>
      ),
    },
    {
      key: "accounting",
      label: { en: "Accounting preview", ar: "المعاينة المحاسبية" },
      content: accountingPreview ? (
        <div className="space-y-4">
          <ImpactPreview
            title={{ en: "Financial Summary", ar: "الملخص المالي" }}
            language={language}
            items={[
              { label: { en: "Subtotal", ar: "المجموع الفرعي" }, value: fmtMoney(Number(accountingPreview.subtotal), accountingPreview.currency_code ?? undefined) },
              { label: { en: "Fees", ar: "الرسوم" }, value: fmtMoney(Number(accountingPreview.fees), accountingPreview.currency_code ?? undefined) },
              { label: { en: "Taxes", ar: "الضرائب" }, value: fmtMoney(Number(accountingPreview.taxes), accountingPreview.currency_code ?? undefined) },
              { label: { en: "Discount", ar: "الخصم" }, value: fmtMoney(Number(accountingPreview.discount), accountingPreview.currency_code ?? undefined) },
              { label: { en: "Total", ar: "الإجمالي" }, value: fmtMoney(Number(accountingPreview.total_amount), accountingPreview.currency_code ?? undefined), tone: "neutral" },
              { label: { en: "Remaining", ar: "المتبقي" }, value: fmtMoney(Number(accountingPreview.remaining), accountingPreview.currency_code ?? undefined), tone: "negative" },
            ]}
          />
          <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" ? "الحساب" : "Account"}</th>
                  <th className="p-3">{language === "ar" ? "النوع" : "Type"}</th>
                  <th className="p-3">{language === "ar" ? "المبلغ" : "Amount"}</th>
                  <th className="p-3">{language === "ar" ? "الوصف" : "Description"}</th>
                </tr>
              </thead>
              <tbody>
                {accountingPreview.lines.map((line, i) => (
                  <tr key={i} className="border-t border-border">
                    <td className="p-3"><span className="font-mono">{line.account_code}</span> · {line.account_name}</td>
                    <td className="p-3 uppercase text-muted-foreground">{line.entry_type}</td>
                    <td className="p-3 font-mono">{fmtMoney(Number(line.amount), accountingPreview.currency_code ?? undefined)}</td>
                    <td className="p-3 text-muted-foreground">{line.description ?? "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ) : (
        <p className="text-sm text-muted-foreground">{language === "ar" ? "تحميل..." : "Loading..."}</p>
      ),
    },
    {
      key: "terms",
      label: { en: "Commercial terms", ar: "الشروط التجارية" },
      content: (
        <div className="grid gap-3 sm:grid-cols-2">
          <Row label={language === "ar" ? "شروط الدفع" : "Payment Terms"} value={order.payment_terms ?? "-"} />
          <Row label={language === "ar" ? "شروط التسليم" : "Delivery Terms"} value={order.delivery_terms ?? "-"} />
          <Row label={language === "ar" ? "مركز التكلفة" : "Cost Center"} value={order.cost_center ?? "-"} />
          <Row label={language === "ar" ? "سعر الصرف" : "Exchange Rate"} value={order.exchange_rate ?? "-"} />
        </div>
      ),
    },
    {
      key: "audit",
      label: { en: "Audit", ar: "التدقيق" },
      content: <AuditHistory entries={auditLogs} language={language} />,
    },
  ]

  return (
    <>
      <EntityDetailPage
        title={order.buy_order_no}
        description={supplierName}
        breadcrumbs={[
          { label: language === "ar" ? "أوامر الشراء" : "Purchase Orders", href: "/purchase-orders" },
          { label: order.buy_order_no },
        ]}
        status={order.status}
        statusLabel={purchaseOrderStatusLabel[order.status] ?? { en: order.status, ar: order.status }}
        statusTone={purchaseOrderStatusTone[order.status]}
        workflow={purchaseOrderWorkflow}
        language={language}
        tabs={tabs}
        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={() => router.push(`/purchase-orders/${order.id}/edit`)}>
                <Pencil className="h-4 w-4" />
                {language === "ar" ? "تعديل" : "Edit"}
              </Button>
            )}
          </div>
        }
        headerExtra={
          <div className="w-full">
            <ActionBar
              definition={purchaseOrderWorkflow}
              status={order.status}
              permissions={permissions}
              language={language}
              permissionMap={purchaseOrderPermissionMap}
              onAction={onActionClick}
              disabled={isSubmitting}
            />
          </div>
        }
      />

      <ActionModal
        open={Boolean(action)}
        action={action}
        language={language}
        entityLabel={order.buy_order_no}
        isSubmitting={isSubmitting}
        onConfirm={handleAction}
        onClose={() => setAction(null)}
      />

      <Modal open={advanceModalOpen} onClose={() => setAdvanceModalOpen(false)} title={language === "ar" ? "تسجيل دفعة مقدمة" : "Record Advance Payment"} description={order.buy_order_no} size="sm">
        <div className="space-y-4">
          <InputField
            id="advance-amount"
            name="amount"
            label={language === "ar" ? "المبلغ" : "Amount"}
            type="number"
            min="0.01"
            step="0.01"
            required
            value={advanceAmount}
            onChange={e => setAdvanceAmount(e.target.value)}
          />
          <InputField
            id="advance-ref"
            name="reference"
            label={language === "ar" ? "المرجع" : "Reference"}
            value={advanceRef}
            onChange={e => setAdvanceRef(e.target.value)}
          />
          <TextAreaField
            id="advance-notes"
            name="notes"
            label={language === "ar" ? "ملاحظات" : "Notes"}
            rows={2}
            value={advanceNotes}
            onChange={e => setAdvanceNotes(e.target.value)}
          />
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setAdvanceModalOpen(false)}>{language === "ar" ? "إغلاق" : "Close"}</Button>
            <Button onClick={handleAdvancePayment} isLoading={isSubmitting}>{language === "ar" ? "تأكيد" : "Confirm"}</Button>
          </div>
        </div>
      </Modal>
    </>
  )
}

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-left font-medium">{value}</span></div>
}

function MoneyRow({ label, value, currency, strong }: { label: string; value: string | number; currency?: string; 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)}</span></div>
}
