'use client'

import { useCallback, useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { RefreshCw } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { useAuth } from "@/contexts/auth-context"
import { useInboundPostings } from "@/hooks/useInboundPostings"
import {
  ActionBar,
  ActionModal,
  type DetailTab,
  EntityDetailPage,
  ImpactPreview,
  type WorkflowAction,
} from "@/components/workflow"
import {
  inboundPostingPermissionMap,
  inboundPostingStatusLabel,
  inboundPostingStatusTone,
  inboundPostingWorkflow,
} from "@/lib/inbound-postings"
import { Button } from "@/components/ui/button"
import { fmtGrams, fmtMoney, formatDateTime } from "@/lib/format"
import { effectivePermissions } from "@/lib/permissions"

export default function InboundPostingDetailPage() {
  const { id } = useParams<{ id: string }>()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { preview, isLoading, isSubmitting, error, getPreview, act } = useInboundPostings()
  const [action, setAction] = useState<WorkflowAction | null>(null)
  const [itemStatus, setItemStatus] = useState<string>("approved")
  const [reviewPassed, setReviewPassed] = useState(false)

  const refresh = useCallback(async () => {
    if (!id) return
    const p = await getPreview(id)
    if (p?.receiving_order_status) setItemStatus(p.receiving_order_status)
    else if (p?.status) setItemStatus(p.status)
  }, [id, getPreview])

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

  if (isLoading && !preview) {
    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 (!preview) {
    return <div className="rounded-lg border border-red-200 bg-red-50 p-6 text-red-700">{error || "Inbound posting not found"}</div>
  }

  const handleAction = async (reason?: string) => {
    if (!action || !id) return
    try {
      await act(id, action.key, reason)
      if (action.key === "review") {
        setReviewPassed(true)
        toast.success(language === "ar" ? "اكتملت المراجعة. أصبح الترحيل متاحًا." : "Review completed. Posting is now available.")
      } else {
        toast.success(language === "ar" ? "تم تنفيذ الإجراء." : "Action completed.")
      }
      setAction(null)
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Action failed")
    }
  }

  const barsAccepted = preview.bars ?? preview.items ?? []
  const inventoryImpact = preview.inventory_impact ?? preview.pool_updates ?? []
  const accountingImpact = preview.journal_entries ?? preview.accounting_impact ?? []
  const permissions = effectivePermissions(user)

  const tabs: DetailTab[] = [
    {
      key: "preview",
      label: { en: "Posting Preview", ar: "معاينة الترحيل" },
      content: (
        <div className="space-y-4">
          <ImpactPreview
            title={{ en: "Inventory Impact", ar: "تأثير المخزون" }}
            language={language}
            items={[
              { label: { en: "Bars Accepted", ar: "السبيكات المقبولة" }, value: String(barsAccepted.length) },
              { label: { en: "Total Weight", ar: "الوزن الإجمالي" }, value: `${fmtGrams(Number(preview.total_weight_grams ?? preview.total_weight ?? 0))} g` },
              { label: { en: "Target Vault", ar: "الخزنة المستهدفة" }, value: preview.target_vault_name ?? preview.vault_name ?? "-" },
              { label: { en: "Target Inventory", ar: "المخزون المستهدف" }, value: "INV-STORE" },
            ]}
          />
          <ImpactPreview
            title={{ en: "Accounting Impact", ar: "التأثير المحاسبي" }}
            language={language}
            items={[
              { label: { en: "Final Cost", ar: "التكلفة النهائية" }, value: fmtMoney(Number(preview.total_cost ?? preview.total_amount ?? 0)) },
              { label: { en: "Journal Entries", ar: "القيود المحاسبية" }, value: String(accountingImpact.length) },
              { label: { en: "Ownership", ar: "الملكية" }, value: "Platform Owned", tone: "positive" },
            ]}
          />
          {barsAccepted.length > 0 && (
            <div>
              <p className="mb-2 text-sm font-semibold">{language === "ar" ? "السبيكات المقبولة" : "Bars Accepted"}</p>
              <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-2">{language === "ar" ? "الباركود" : "Bar Code"}</th>
                      <th className="p-2">{language === "ar" ? "الوزن" : "Weight"}</th>
                      <th className="p-2">{language === "ar" ? "العيار" : "Purity"}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {barsAccepted.map((bar: any, i: number) => (
                      <tr key={bar.id ?? i} className="border-t border-border">
                        <td className="p-2 font-mono">{bar.bar_code ?? bar.external_bar_no ?? "-"}</td>
                        <td className="p-2 font-mono">{fmtGrams(Number(bar.weight_grams ?? bar.actual_weight_grams ?? 0))}</td>
                        <td className="p-2">{bar.purity_name ?? bar.karat ?? "-"}K</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      ),
    },
    {
      key: "audit",
      label: { en: "Audit", ar: "التدقيق" },
      content: (
        <div className="space-y-2">
          <div className="border-l-2 border-gold-300 pl-3">
            <strong className="text-sm">Created</strong>
            <span className="text-[11px] text-muted-foreground block">{preview.created_at ? formatDateTime(preview.created_at) : "-"}</span>
          </div>
          {preview.posted_at && (
            <div className="border-l-2 border-emerald-300 pl-3">
              <strong className="text-sm">Posted</strong>
              <span className="text-[11px] text-muted-foreground block">{formatDateTime(preview.posted_at)}</span>
            </div>
          )}
        </div>
      ),
    },
  ]

  return (
    <>
      <EntityDetailPage
        title={preview.receiving_order_no ?? preview.order_no ?? id}
        description={language === "ar" ? "أمر التوريد المخزني" : "Stock Supply Order"}
        breadcrumbs={[
          { label: language === "ar" ? "أمر التوريد المخزني" : "Stock Supply Order", href: "/inbound-postings" },
          { label: preview.receiving_order_no ?? id },
        ]}
        status={itemStatus}
        statusLabel={inboundPostingStatusLabel[itemStatus] ?? { en: itemStatus, ar: itemStatus }}
        statusTone={inboundPostingStatusTone[itemStatus] ?? "neutral"}
        workflow={inboundPostingWorkflow}
        language={language}
        tabs={tabs}
        actions={
          <Button variant="outline" onClick={() => { setReviewPassed(false); refresh() }} disabled={isLoading}>
            <RefreshCw className="h-4 w-4" />
          </Button>
        }
        headerExtra={
          <div className="w-full">
            <ActionBar
              definition={inboundPostingWorkflow}
              status={itemStatus}
              permissions={permissions}
              language={language}
              permissionMap={inboundPostingPermissionMap}
              onAction={setAction}
              disabled={isSubmitting}
              disabledActions={!reviewPassed && itemStatus === "approved" ? ["post"] : []}
            />
          </div>
        }
      />

      <ActionModal
        open={Boolean(action)}
        action={action}
        language={language}
        entityLabel={preview.receiving_order_no ?? id}
        isSubmitting={isSubmitting}
        onConfirm={handleAction}
        onClose={() => setAction(null)}
      >
        {action?.key === "post" && (
          <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">
            {language === "ar"
              ? "سيتم تحديث المخزون وإنشاء القيود المحاسبية وتغيير الملكية إلى المنصة."
              : "This will update inventory, create accounting entries, and change ownership to Platform."}
          </div>
        )}
      </ActionModal>
    </>
  )
}
