'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import type { ReactNode } from "react"
import { useParams, useRouter } from "next/navigation"
import { ArrowLeft, Ban, CheckCircle2, FileCheck2, Printer, RefreshCw, RotateCcw, Send, ShieldCheck, Truck, XCircle } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { useAuth } from "@/contexts/auth-context"
import { buyErrorMessage, printBuyVoucher, useBuyOrders } from "@/hooks/useBuyOrders"
import { allowedBuyActions, buyStatusLabel, buyStatusTone, buyTypeLabel, buyWorkflowPermissionsForUser, type BuyAction } from "@/lib/buy-orders"
import type { BuyOrderPostingResult, BuyOrderStatus } 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, TextAreaField } from "@/components/ui/FormFields"
import { fmtMoney, fmtGrams, formatDateTime } from "@/lib/format"

const actionLabel: Record<BuyAction, { en: string; ar: string }> = {
  recalculate: { en: "Recalculate", ar: "إعادة الاحتساب" },
  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 approval", ar: "ترحيل الاعتماد" },
  send: { en: "Send to supplier", ar: "إرسال للمورد" },
  partial: { en: "Mark partially supplied", ar: "توريد جزئي" },
  full: { en: "Mark fully supplied", ar: "توريد كامل" },
  close: { en: "Close", ar: "إغلاق" },
  "post-supply": { en: "Post supply", ar: "ترحيل التوريد" },
  "post-buyback": { en: "Post buyback", ar: "ترحيل شراء العميل" },
  reverse: { en: "Reverse posting", ar: "عكس الترحيل" },
}

const actionIcon: Record<BuyAction, typeof Send> = {
  recalculate: RefreshCw,
  submit: Send,
  review: ShieldCheck,
  approve: CheckCircle2,
  reject: XCircle,
  cancel: Ban,
  post: FileCheck2,
  send: Truck,
  partial: Truck,
  full: Truck,
  close: CheckCircle2,
  "post-supply": FileCheck2,
  "post-buyback": FileCheck2,
  reverse: RotateCcw,
}

const priorityLabel: Record<string, { en: string; ar: string }> = {
  low: { en: "Low", ar: "منخفضة" },
  normal: { en: "Normal", ar: "عادية" },
  high: { en: "High", ar: "عالية" },
  urgent: { en: "Urgent", ar: "عاجلة" },
}

function requiresReason(action: BuyAction | null) {
  return action === "reject" || action === "cancel" || action === "reverse"
}

function isPostingResult(value: unknown): value is BuyOrderPostingResult {
  return Boolean(value && typeof value === "object" && "order_no" in value && ("journal_entries" in value || "reversed_journals" in value))
}

export default function BuyOrderDetailPage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { selected, support, isLoading, isSubmitting, error, get, loadSupport, act, recalculate } = useBuyOrders()
  const [actionOpen, setActionOpen] = useState(false)
  const [selectedAction, setSelectedAction] = useState<BuyAction | null>(null)
  const [reason, setReason] = useState("")
  const [receivingVaultId, setReceivingVaultId] = useState("")
  const [customerUserId, setCustomerUserId] = useState("")
  const [postingResult, setPostingResult] = useState<BuyOrderPostingResult | null>(null)

  const id = params.id

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

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

  const actions = useMemo(() => {
    if (!selected) return []
    return allowedBuyActions(selected.status as BuyOrderStatus, buyWorkflowPermissionsForUser(user), selected.buy_order_type)
  }, [selected, user?.permissions])

  const openAction = (action: BuyAction) => {
    if (action === "recalculate") {
      recalculate(id)
        .then(() => {
          toast.success(language === "ar" ? "تمت إعادة الاحتساب." : "Order recalculated.")
          refresh()
        })
        .catch(err => toast.error(buyErrorMessage(err)))
      return
    }
    setSelectedAction(action)
    setReason("")
    setReceivingVaultId(selected?.target_vault_id || "")
    setCustomerUserId("")
    setActionOpen(true)
  }

  const submitAction = async () => {
    if (!selectedAction) return
    if (requiresReason(selectedAction) && !reason.trim()) {
      toast.error(language === "ar" ? "السبب مطلوب." : "Reason is required.")
      return
    }
    try {
      const result = await act(id, selectedAction, {
        reason: reason.trim() || undefined,
        receiving_vault_id: receivingVaultId || undefined,
        customer_user_id: customerUserId.trim() || undefined,
      })
      if (isPostingResult(result)) setPostingResult(result)
      toast.success(language === "ar" ? "تم تنفيذ الإجراء." : "Action completed.")
      setActionOpen(false)
      setSelectedAction(null)
      await refresh()
    } catch (err) {
      toast.error(buyErrorMessage(err))
    }
  }

  const printVoucher = () => {
    if (!support.voucher) {
      toast.error(language === "ar" ? "السند غير جاهز بعد." : "Voucher is not ready yet.")
      return
    }
    try {
      printBuyVoucher(support.voucher, `${support.voucher.order_no}-buy-voucher`)
      toast.success(language === "ar" ? "تم فتح عرض الطباعة." : "Voucher print view opened.")
    } catch (err) {
      toast.error(buyErrorMessage(err))
    }
  }

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

  if (!selected) {
    return (
      <div className="space-y-4">
        <Button variant="outline" onClick={() => router.push("/buy-orders")}><ArrowLeft className="h-4 w-4" />{language === "ar" ? "رجوع" : "Back"}</Button>
        <div className="rounded-lg border border-red-200 bg-red-50 p-4 text-sm text-red-700">{error || (language === "ar" ? "لم يتم العثور على أمر الشراء." : "Buy order was not found.")}</div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={`${language === "ar" ? "أمر شراء" : "Buy order"} ${selected.buy_order_no}`}
        description={buyTypeLabel[selected.buy_order_type]?.[language] ?? selected.buy_order_type}
        breadcrumbs={[
          { label: language === "ar" ? "أوامر الشراء" : "Buy orders", href: "/buy-orders" },
          { label: selected.buy_order_no },
        ]}
        actions={
          <div className="flex flex-wrap gap-2">
            <Button variant="outline" onClick={() => router.push("/buy-orders")}><ArrowLeft className="h-4 w-4" />{language === "ar" ? "رجوع" : "Back"}</Button>
            <Button variant="outline" onClick={refresh} disabled={isLoading}><RefreshCw className="h-4 w-4" /></Button>
            {buyWorkflowPermissionsForUser(user).includes("buy_orders:print") && <Button variant="outline" onClick={printVoucher}><Printer className="h-4 w-4" />{language === "ar" ? "طباعة" : "Print"}</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 lg:grid-cols-[1fr_360px]">
        <div className="space-y-6">
          <SectionCard title={language === "ar" ? "ملخص الأمر" : "Order summary"}>
            <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
              <Info label={language === "ar" ? "الحالة" : "Status"} value={<StatusBadge tone={buyStatusTone[selected.status as BuyOrderStatus] ?? "neutral"}>{buyStatusLabel[selected.status as BuyOrderStatus]?.[language] ?? selected.status}</StatusBadge>} />
              <Info label={language === "ar" ? "الأولوية" : "Priority"} value={priorityLabel[selected.priority]?.[language] ?? selected.priority} />
              <Info label={language === "ar" ? "المورد" : "Supplier"} value={selected.supplier_id || "-"} />
              <Info label={language === "ar" ? "العميل" : "Customer"} value={selected.customer_id || "-"} />
              <Info label={language === "ar" ? "الفرع" : "Branch"} value={selected.target_branch_id || "-"} />
              <Info label={language === "ar" ? "الخزنة" : "Vault"} value={selected.target_vault_id || "-"} />
              <Info label={language === "ar" ? "مرجع المورد" : "Supplier ref"} value={selected.supplier_reference || "-"} />
              <Info label={language === "ar" ? "مرجع خارجي" : "External ref"} value={selected.external_reference || "-"} />
              <Info label={language === "ar" ? "تم الإنشاء" : "Created"} value={formatDateTime(selected.created_at)} />
              <Info label={language === "ar" ? "اعتمد" : "Approved"} value={selected.approved_at ? formatDateTime(selected.approved_at) : "-"} />
              <Info label={language === "ar" ? "رحل" : "Posted"} value={selected.posted_at ? formatDateTime(selected.posted_at) : "-"} />
              <Info label={language === "ar" ? "أغلق" : "Closed"} value={selected.closed_at ? formatDateTime(selected.closed_at) : "-"} />
            </div>
          </SectionCard>

          <SectionCard title={language === "ar" ? "بنود الذهب" : "Gold items"} padded={false}>
            <div className="overflow-auto">
              <table className="w-full min-w-[760px] text-sm">
                <thead className="border-b border-border bg-muted/40 text-left text-xs text-muted-foreground">
                  <tr>
                    <th className="px-4 py-3">#</th>
                    <th className="px-4 py-3">{language === "ar" ? "النوع" : "Metal"}</th>
                    <th className="px-4 py-3">{language === "ar" ? "الوزن" : "Weight"}</th>
                    <th className="px-4 py-3">{language === "ar" ? "الكمية" : "Qty"}</th>
                    <th className="px-4 py-3">{language === "ar" ? "سعر الجرام" : "Price/g"}</th>
                    <th className="px-4 py-3">{language === "ar" ? "العلاوة" : "Premium"}</th>
                    <th className="px-4 py-3">{language === "ar" ? "الإجمالي" : "Total"}</th>
                  </tr>
                </thead>
                <tbody>
                  {(selected.items ?? []).map((item, index) => (
                    <tr key={item.id} className="border-b border-border/60">
                      <td className="px-4 py-3">{index + 1}</td>
                      <td className="px-4 py-3">{item.metal_type}</td>
                      <td className="px-4 py-3 font-mono">{fmtGrams(Number(item.weight_grams))}</td>
                      <td className="px-4 py-3 font-mono">{item.quantity}</td>
                      <td className="px-4 py-3 font-mono">{fmtMoney(Number(item.price_per_gram))}</td>
                      <td className="px-4 py-3 font-mono">{fmtMoney(Number(item.premium))}</td>
                      <td className="px-4 py-3 font-mono font-semibold">{fmtMoney(Number(item.line_total))}</td>
                    </tr>
                  ))}
                  {(!selected.items || selected.items.length === 0) && (
                    <tr><td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">{language === "ar" ? "لا توجد بنود." : "No items."}</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </SectionCard>

          <div className="grid gap-6 lg:grid-cols-2">
            <SectionCard title={language === "ar" ? "سجل الحالات" : "Status history"}>
              <div className="space-y-2">
                {support.history.map((entry: any) => (
                  <div key={entry.id} className="rounded-lg border border-border bg-muted/20 p-3 text-sm">
                    <div className="flex justify-between gap-3">
                      <strong>{entry.old_status || "-"} {"->"} {entry.new_status}</strong>
                      <span className="text-xs text-muted-foreground">{formatDateTime(entry.changed_at)}</span>
                    </div>
                    {entry.note && <p className="mt-1 text-xs text-muted-foreground">{entry.note}</p>}
                  </div>
                ))}
                {support.history.length === 0 && <p className="text-sm text-muted-foreground">{language === "ar" ? "لا يوجد سجل حالات." : "No status history."}</p>}
              </div>
            </SectionCard>

            <SectionCard title={language === "ar" ? "الاعتمادات" : "Approvals"}>
              <div className="space-y-3">
                {support.approvals.map((approval: any) => (
                  <div key={approval.id} className="rounded-lg border border-border bg-muted/20 p-3 text-sm">
                    <div className="flex justify-between">
                      <strong>{approval.approval_type}</strong>
                      <StatusBadge tone={approval.status === "approved" ? "success" : approval.status === "rejected" ? "danger" : "pending"}>{approval.status}</StatusBadge>
                    </div>
                    <div className="mt-2 space-y-1">
                      {(approval.steps ?? []).map((step: any) => <div key={step.id} className="flex justify-between text-xs text-muted-foreground"><span>Step {step.step_order}</span><span>{step.status}</span></div>)}
                    </div>
                  </div>
                ))}
                {support.approvals.length === 0 && <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد طلبات اعتماد." : "No approval requests."}</p>}
              </div>
            </SectionCard>
          </div>

          <SectionCard title={language === "ar" ? "نتائج الترحيل" : "Posting results"}>
            <PostingBlock result={postingResult || support.postings} language={language} />
          </SectionCard>
        </div>

        <div className="space-y-6">
          <SectionCard title={language === "ar" ? "الملخص المالي" : "Financial summary"}>
            <div className="space-y-3">
              <MoneyRow label={language === "ar" ? "الإجمالي الفرعي" : "Subtotal"} value={selected.subtotal_amount} />
              <MoneyRow label={language === "ar" ? "الرسوم" : "Fees"} value={selected.fee_amount} />
              <MoneyRow label={language === "ar" ? "الضريبة" : "Tax"} value={selected.tax_amount} />
              <MoneyRow label={language === "ar" ? "الخصم" : "Discount"} value={selected.discount_amount} />
              <div className="border-t border-border pt-3"><MoneyRow label={language === "ar" ? "الإجمالي" : "Total"} value={selected.total_amount} strong /></div>
            </div>
          </SectionCard>

          <SectionCard title={language === "ar" ? "إجراءات سير العمل" : "Workflow actions"}>
            <div className="grid gap-2">
              {actions.length === 0 ? (
                <div className="rounded-md border border-border bg-muted/30 px-3 py-2 text-sm text-muted-foreground">{language === "ar" ? "لا توجد إجراءات متاحة." : "No available actions."}</div>
              ) : (
                actions.map(action => {
                  const Icon = actionIcon[action]
                  return (
                    <Button key={action} variant={action === "reject" || action === "cancel" || action === "reverse" ? "outline" : "primary"} onClick={() => openAction(action)} disabled={isSubmitting}>
                      <Icon className="h-4 w-4" />
                      {actionLabel[action][language]}
                    </Button>
                  )
                })
              )}
            </div>
          </SectionCard>

          <SectionCard title={language === "ar" ? "سجلات التدقيق" : "Audit logs"}>
            <div className="max-h-[360px] space-y-2 overflow-auto pr-1">
              {support.auditLogs.map((log: any, index) => (
                <div key={log.id || index} className="rounded-lg border border-border bg-muted/20 p-3 text-xs">
                  <div className="flex justify-between gap-3">
                    <strong>{String(log.action || "audit").replace(/_/g, " ").toUpperCase()}</strong>
                    <span className="text-muted-foreground">{formatDateTime(log.created_at)}</span>
                  </div>
                </div>
              ))}
              {support.auditLogs.length === 0 && <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد سجلات تدقيق." : "No audit logs."}</p>}
            </div>
          </SectionCard>
        </div>
      </div>

      <Modal open={actionOpen} onClose={() => setActionOpen(false)} title={selectedAction ? actionLabel[selectedAction][language] : ""} size="sm">
        <div className="space-y-4">
          {selectedAction === "post-supply" && (
            <InputField id="receiving_vault_id" name="receiving_vault_id" label={language === "ar" ? "خزنة الاستلام" : "Receiving vault ID"} value={receivingVaultId} onChange={event => setReceivingVaultId(event.target.value)} />
          )}
          {selectedAction === "post-buyback" && (
            <div className="rounded-lg border border-border bg-muted/30 p-3 text-sm text-muted-foreground">
              {language === "ar"
                ? "سيتم استخدام العميل المرتبط بأمر الشراء تلقائياً. لا تحتاج لإدخال معرف يدوي."
                : "The customer linked to this buy order will be used automatically. No manual ID is required."}
            </div>
          )}
          <TextAreaField id="reason" name="reason" label={requiresReason(selectedAction) ? (language === "ar" ? "السبب" : "Reason") : (language === "ar" ? "ملاحظة" : "Note")} value={reason} rows={4} onChange={event => setReason(event.target.value)} required={requiresReason(selectedAction)} />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setActionOpen(false)}>{language === "ar" ? "إغلاق" : "Close"}</Button>
            <Button variant={selectedAction === "reject" || selectedAction === "cancel" || selectedAction === "reverse" ? "danger" : "primary"} onClick={submitAction} isLoading={isSubmitting}>
              {selectedAction ? actionLabel[selectedAction][language] : (language === "ar" ? "تأكيد" : "Confirm")}
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

function Info({ label, value }: { label: string; value: ReactNode }) {
  return (
    <div>
      <p className="text-xs uppercase tracking-wide text-muted-foreground">{label}</p>
      <div className="mt-1 text-sm font-medium">{value}</div>
    </div>
  )
}

function MoneyRow({ label, value, strong }: { label: string; value: string; strong?: boolean }) {
  return (
    <div className="flex items-center justify-between gap-3">
      <span className="text-sm text-muted-foreground">{label}</span>
      <span className={`font-mono tabular-nums ${strong ? "text-lg font-bold" : "font-semibold"}`}>{fmtMoney(Number(value || 0))}</span>
    </div>
  )
}

function PostingBlock({ result, language }: { result: BuyOrderPostingResult | null; language: "en" | "ar" }) {
  if (!result) return <p className="text-sm text-muted-foreground">{language === "ar" ? "لم يتم إنشاء ترحيلات بعد." : "No posting records yet."}</p>
  const journals = result.journal_entries ?? []
  const reversed = result.reversed_journals ?? []
  const gold = result.gold_postings ?? []
  const cash = result.cash_postings ?? []
  return (
    <div className="grid gap-3 md:grid-cols-2">
      <PostList title={language === "ar" ? "قيود اليومية" : "Journal entries"} rows={journals} empty={language === "ar" ? "لا توجد قيود." : "No journals."} />
      <PostList title={language === "ar" ? "القيود المعكوسة" : "Reversals"} rows={reversed} empty={language === "ar" ? "لا توجد قيود معكوسة." : "No reversals."} />
      <PostList title={language === "ar" ? "حركات الذهب" : "Gold postings"} rows={gold} empty={language === "ar" ? "لا توجد حركات ذهب." : "No gold postings."} />
      <PostList title={language === "ar" ? "حركات النقد" : "Cash postings"} rows={cash} empty={language === "ar" ? "لا توجد حركات نقدية." : "No cash postings."} />
    </div>
  )
}

function PostList({ title, rows, empty }: { title: string; rows: Record<string, unknown>[]; empty: string }) {
  return (
    <div className="rounded-lg border border-border bg-muted/20 p-3">
      <p className="mb-2 text-sm font-semibold">{title}</p>
      {rows.length ? (
        <ul className="space-y-2">
          {rows.map((row, index) => (
            <li key={index} className="rounded bg-background p-2 text-xs text-muted-foreground">
              {Object.entries(row).slice(0, 4).map(([key, value]) => <div key={key} className="flex justify-between gap-2"><span>{key}</span><span className="font-mono text-right">{String(value ?? "-")}</span></div>)}
            </li>
          ))}
        </ul>
      ) : <p className="text-xs text-muted-foreground">{empty}</p>}
    </div>
  )
}
