'use client'

import { useCallback, useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { RefreshCw, Snowflake, Unlock } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { useAuth } from "@/contexts/auth-context"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import { EntityDetailPage, type DetailTab, AuditHistory, type AuditEntry } from "@/components/workflow"
import { StatusBadge } from "@/components/ui/status-badge"
import { Button } from "@/components/ui/button"
import { Modal } from "@/components/ui/modal"
import { TextAreaField } from "@/components/ui/FormFields"
import { fmtGrams, fmtMoney, formatDateTime } from "@/lib/format"
import type { PaginatedResponse } from "@/types"

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

const barStatusTone: Record<string, any> = {
  available: "success",
  reserved: "warning",
  blocked: "danger",
  in_transit: "processing",
  delivered: "info",
  sold: "neutral",
  pending_inspection: "pending",
  allocated_to_pool: "processing",
}

const statusText: Record<string, { ar: string; en: string }> = {
  available: { ar: "متاحة", en: "Available" },
  reserved: { ar: "محجوزة", en: "Reserved" },
  blocked: { ar: "مجمّدة", en: "Blocked" },
  in_transit: { ar: "قيد النقل", en: "In transit" },
  delivered: { ar: "مسلّمة", en: "Delivered" },
  pending_inspection: { ar: "بانتظار الفحص", en: "Pending inspection" },
  in_custody: { ar: "في الأمانات", en: "In custody" },
}

export default function BullionBarDetailPage() {
  const { id } = useParams<{ id: string }>()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const [bar, setBar] = useState<any>(null)
  const [movements, setMovements] = useState<any[]>([])
  const [ownership, setOwnership] = useState<any[]>([])
  const [auditLogs, setAuditLogs] = useState<AuditEntry[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [freezeModalOpen, setFreezeModalOpen] = useState(false)
  const [freezeReason, setFreezeReason] = useState("")

  const refresh = useCallback(async () => {
    if (!id) return
    setIsLoading(true)
    try {
      const [barRes, movRes, ownRes, auditRes] = await Promise.allSettled([
        api.get(ENDPOINTS.BULLION_BARS.GET_BY_ID(id)),
        api.get(ENDPOINTS.BULLION_BARS.MOVEMENTS(id)),
        api.get(ENDPOINTS.BULLION_BARS.OWNERSHIP(id)),
        api.get(ENDPOINTS.BULLION_BARS.AUDIT(id)),
      ])

      if (barRes.status === "fulfilled") {
        const barData = barRes.value?.data ?? barRes.value
        setBar(barData)
      }
      if (movRes.status === "fulfilled") setMovements(arrayPayload<any>(movRes.value))
      if (ownRes.status === "fulfilled") setOwnership(arrayPayload<any>(ownRes.value))
      if (auditRes.status === "fulfilled") setAuditLogs(arrayPayload<AuditEntry>(auditRes.value))
    } catch (err: any) {
      toast.error(err?.message || "Failed to load bar")
    } finally {
      setIsLoading(false)
    }
  }, [id])

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

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

  const handleFreeze = async () => {
    if (!id) return
    setIsSubmitting(true)
    try {
      await api.post(ENDPOINTS.BULLION_BARS.FREEZE(id), { reason: freezeReason })
      toast.success(language === "ar" ? "تم تجميد السبيكة." : "Bar frozen.")
      setFreezeModalOpen(false)
      setFreezeReason("")
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to freeze")
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleUnfreeze = async () => {
    if (!id) return
    setIsSubmitting(true)
    try {
      await api.post(ENDPOINTS.BULLION_BARS.UNFREEZE(id))
      toast.success(language === "ar" ? "تم إلغاء تجميد السبيكة." : "Bar unfrozen.")
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to unfreeze")
    } finally {
      setIsSubmitting(false)
    }
  }

  const isFrozen = bar.status === "blocked" || bar.block_reason

  const tabs: DetailTab[] = [
    {
      key: "overview",
      label: { en: "Overview", ar: "نظرة عامة" },
      content: (
        <div className="grid gap-3 sm:grid-cols-2">
          <Row label={language === "ar" ? "الباركود" : "Bar Code"} value={bar.bar_code} />
          <Row label={language === "ar" ? "الرقم التسلسلي" : "Serial Number"} value={bar.serial_number ?? "-"} />
          <Row label={language === "ar" ? "المعدن" : "Metal"} value={bar.metal_type ?? "gold"} />
          <Row label={language === "ar" ? "العيار" : "Purity"} value={bar.purity_name ?? "-"} />
          <Row label={language === "ar" ? "الوزن" : "Weight"} value={`${fmtGrams(Number(bar.weight_grams ?? bar.weight ?? 0))} g`} />
          <Row label={language === "ar" ? "الحالة" : "Status"} value={statusText[bar.status]?.[language] ?? bar.status} />
          <Row label={language === "ar" ? "المخزون الحالي" : "Current Inventory"} value={bar.current_inventory ?? "-"} />
          <Row label={language === "ar" ? "محجوزة" : "Reserved"} value={bar.is_reserved ? (language === "ar" ? "نعم" : "Yes") : (language === "ar" ? "لا" : "No")} />
          <Row label={language === "ar" ? "حالة الفحص" : "Inspection Status"} value={bar.inspection_status ?? "-"} />
          <Row label={language === "ar" ? "الخزنة" : "Vault"} value={bar.vault_name ?? "-"} />
          <Row label={language === "ar" ? "الفرع" : "Branch"} value={bar.branch_name ?? "-"} />
          <Row label={language === "ar" ? "نوع الملكية" : "Owner Type"} value={bar.current_owner_type === "platform" ? (language === "ar" ? "المنصة" : "Platform") : (language === "ar" ? "عميل" : "Customer")} />
          <Row label={language === "ar" ? "المصدر" : "Source"} value={bar.source_type ?? "-"} />
          <Row label={language === "ar" ? "آخر حركة" : "Last Movement"} value={bar.last_movement_type ?? "-"} />
          <Row label={language === "ar" ? "وقت آخر حركة" : "Last Movement At"} value={bar.last_movement_at ? formatDateTime(bar.last_movement_at) : "-"} />
          <Row label={language === "ar" ? "الإنشاء" : "Created"} value={formatDateTime(bar.created_at)} />
          {bar.notes && <div className="sm:col-span-2"><Row label={language === "ar" ? "ملاحظات" : "Notes"} value={bar.notes} /></div>}
        </div>
      ),
    },
    {
      key: "movements",
      label: { en: "Movements", ar: "الحركات" },
      content: (
        <div className="space-y-2">
          {movements.length === 0 ? (
            <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد حركات." : "No movements."}</p>
          ) : (
            movements.map((m, i) => (
              <div key={m.id ?? i} className="border-l-2 border-gold-300 pl-3">
                <div className="flex justify-between">
                  <strong className="text-sm">{m.movement_type ?? m.action ?? "-"}</strong>
                  <span className="text-[11px] text-muted-foreground">{m.created_at ? formatDateTime(m.created_at) : "-"}</span>
                </div>
                <p className="text-xs text-muted-foreground">{m.from_vault_name ?? "-"} → {m.to_vault_name ?? "-"}</p>
                {m.quantity && <p className="text-xs text-muted-foreground">{fmtGrams(Number(m.quantity))} g · {m.from_status ?? "-"} → {m.to_status ?? "-"}</p>}
                {m.reason && <p className="text-xs text-muted-foreground">{m.reason}</p>}
              </div>
            ))
          )}
        </div>
      ),
    },
    {
      key: "ownership",
      label: { en: "Ownership", ar: "الملكية" },
      content: (
        <div className="space-y-2">
          {ownership.length === 0 ? (
            <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد سجلات ملكية." : "No ownership records."}</p>
          ) : (
            ownership.map((o, i) => (
              <div key={o.id ?? i} className="rounded-lg border border-border p-3 text-sm">
                <div className="flex justify-between">
                  <strong>{o.owner_type === "platform" ? (language === "ar" ? "المنصة" : "Platform") : (language === "ar" ? "عميل" : "Customer")}</strong>
                  <span className="text-[11px] text-muted-foreground">{o.acquired_at ? formatDateTime(o.acquired_at) : "-"}</span>
                </div>
                {o.owner_id && <p className="text-xs text-muted-foreground">ID: {o.owner_id}</p>}
              </div>
            ))
          )}
        </div>
      ),
    },
    {
      key: "inspection",
      label: { en: "Inspection", ar: "الفحص" },
      content: (
        <div className="grid gap-3 sm:grid-cols-2">
          <Row label={language === "ar" ? "حالة الفحص" : "Inspection Status"} value={bar.inspection_status ?? "-"} />
          <Row label={language === "ar" ? "العيار المعتمد" : "Approved Purity"} value={bar.purity_name ?? "-"} />
          <Row label={language === "ar" ? "الوزن المعتمد" : "Approved Weight"} value={`${fmtGrams(Number(bar.weight ?? 0))} g`} />
          <Row label={language === "ar" ? "رقم الشهادة" : "Certificate No."} value={bar.certificate_no ?? "-"} />
          <Row label={language === "ar" ? "سبب الحظر" : "Block Reason"} value={bar.block_reason ?? "-"} />
        </div>
      ),
    },
    {
      key: "costing",
      label: { en: "Costing", ar: "التكلفة" },
      content: (
        <div className="grid gap-3 sm:grid-cols-2">
          <Row label={language === "ar" ? "تكلفة الشراء" : "Purchase Cost"} value={bar.purchase_cost ? fmtMoney(Number(bar.purchase_cost)) : "-"} />
          <Row label={language === "ar" ? "التكلفة الإجمالية" : "Total Cost"} value={bar.total_cost ? fmtMoney(Number(bar.total_cost)) : "-"} />
          <Row label={language === "ar" ? "تكلفة الجرام" : "Cost per Gram"} value={bar.total_cost && bar.weight ? fmtMoney(Number(bar.total_cost) / Number(bar.weight)) : "-"} />
        </div>
      ),
    },
    {
      key: "attachments",
      label: { en: "Attachments", ar: "المرفقات" },
      content: <p className="text-sm text-muted-foreground">{language === "ar" ? "لا توجد مرفقات مرتبطة بهذه السبيكة." : "No attachments are linked to this bar."}</p>,
    },
    {
      key: "audit",
      label: { en: "Audit", ar: "التدقيق" },
      content: <AuditHistory entries={auditLogs} language={language} />,
    },
  ]

  return (
    <>
      <EntityDetailPage
        title={bar.bar_code}
        description={bar.serial_number ?? ""}
        breadcrumbs={[
          { label: language === "ar" ? "سجل السبيكات" : "Bullion Registry", href: "/bullion-bars" },
          { label: bar.bar_code },
        ]}
        status={bar.status}
        statusLabel={statusText[bar.status] ?? { en: bar.status, ar: bar.status }}
        statusTone={barStatusTone[bar.status] ?? "neutral"}
        language={language}
        tabs={tabs}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={refresh} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
            </Button>
            {isFrozen ? (
              <Button variant="outline" onClick={handleUnfreeze} disabled={isSubmitting}>
                <Unlock className="h-4 w-4" />
                {language === "ar" ? "إلغاء التجميد" : "Unfreeze"}
              </Button>
            ) : (
              <Button variant="outline" onClick={() => setFreezeModalOpen(true)}>
                <Snowflake className="h-4 w-4" />
                {language === "ar" ? "تجميد" : "Freeze"}
              </Button>
            )}
          </div>
        }
      />

      <Modal open={freezeModalOpen} onClose={() => setFreezeModalOpen(false)} title={language === "ar" ? "تجميد السبيكة" : "Freeze Bar"} description={bar.bar_code} size="sm">
        <div className="space-y-4">
          <TextAreaField
            id="freeze-reason"
            name="reason"
            label={language === "ar" ? "السبب" : "Reason"}
            required
            rows={3}
            value={freezeReason}
            onChange={e => setFreezeReason(e.target.value)}
          />
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setFreezeModalOpen(false)}>{language === "ar" ? "إلغاء" : "Cancel"}</Button>
            <Button variant="danger" onClick={handleFreeze} 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>
}
