'use client'

import { useCallback, useEffect, useState } from "react"
import { useParams, useRouter } from "next/navigation"
import { ExternalLink, RefreshCw } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { useAuth } from "@/contexts/auth-context"
import { useSupplierShipments } from "@/hooks/useSupplierShipments"
import {
  ActionBar,
  ActionModal,
  type AuditEntry,
  AuditHistory,
  type DetailTab,
  EntityDetailPage,
  type WorkflowAction,
} from "@/components/workflow"
import {
  supplierShipmentPermissionMap,
  supplierShipmentStatusLabel,
  supplierShipmentStatusTone,
  supplierShipmentWorkflow,
} from "@/lib/supplier-shipments"
import type { SupplierDTO, SupplierShipment, VaultDTO } from "@/types"
import { Button } from "@/components/ui/button"
import { fmtGrams, fmtMoney, formatDateTime } from "@/lib/format"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import type { PaginatedResponse } from "@/types"
import { effectivePermissions } from "@/lib/permissions"

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

function shipmentLifecycleAudit(shipment: SupplierShipment, language: "ar" | "en"): AuditEntry[] {
  const entries: AuditEntry[] = []
  entries.push({
    id: `${shipment.id}-created`,
    action: language === "ar" ? "إنشاء الشحنة" : "Shipment created",
    entity_type: "supplier_shipment",
    entity_id: shipment.id,
    new_values: { status: "draft", shipment_no: shipment.shipment_no },
    created_at: shipment.created_at,
  })
  if (shipment.dispatched_at) {
    entries.push({
      id: `${shipment.id}-dispatched`,
      action: language === "ar" ? "تأكيد الإرسال" : "Dispatch confirmed",
      entity_type: "supplier_shipment",
      entity_id: shipment.id,
      old_values: { status: "draft" },
      new_values: { status: "dispatched" },
      created_at: shipment.dispatched_at,
    })
  }
  if (shipment.arrived_at) {
    entries.push({
      id: `${shipment.id}-arrived`,
      action: language === "ar" ? "تأكيد الوصول" : "Arrival confirmed",
      entity_type: "supplier_shipment",
      entity_id: shipment.id,
      new_values: { status: "arrived" },
      created_at: shipment.arrived_at,
    })
  }
  if (shipment.closed_at) {
    entries.push({
      id: `${shipment.id}-closed`,
      action: language === "ar" ? "إغلاق الشحنة" : "Shipment closed",
      entity_type: "supplier_shipment",
      entity_id: shipment.id,
      new_values: { status: "closed" },
      created_at: shipment.closed_at,
    })
  }
  return entries.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
}

export default function SupplierShipmentDetailPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { selected: shipment, isLoading, isSubmitting, error, get, act } = useSupplierShipments()
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [vaults, setVaults] = useState<VaultDTO[]>([])
  const [action, setAction] = useState<WorkflowAction | null>(null)
  const [auditLogs, setAuditLogs] = useState<AuditEntry[]>([])

  const refresh = useCallback(async () => {
    if (!id) return
    const fresh = await get(id)
    try {
      const res = await api.get(ENDPOINTS.AUDIT_LOGS.LIST, { params: { entity_type: "supplier_shipment", entity_id: id } })
      const logs = arrayPayload<AuditEntry>(res)
      setAuditLogs(logs.length ? logs : fresh ? shipmentLifecycleAudit(fresh, language) : [])
    } catch { setAuditLogs(fresh ? shipmentLifecycleAudit(fresh, language) : []) }
  }, [id, get, language])

  useEffect(() => {
    refresh()
    Promise.all([
      api.get("/suppliers/"),
      api.get("/warehouse/vaults"),
    ])
      .then(([s, v]) => {
        setSuppliers(arrayPayload<SupplierDTO>(s))
        setVaults(arrayPayload<VaultDTO>(v))
      })
      .catch(() => undefined)
  }, [refresh])

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

  const supplier = suppliers.find(s => s.id === shipment.supplier_id)
  const vault = vaults.find(v => v.id === shipment.target_vault_id)
  const supplierName = supplier ? (language === "ar" ? supplier.name_ar : supplier.name_en || supplier.name_ar) : "-"
  const permissions = effectivePermissions(user)

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

  const tabs: DetailTab[] = [
    {
      key: "details",
      label: { en: "Shipment details", ar: "تفاصيل الشحنة" },
      content: (
        <div className="grid gap-3 sm:grid-cols-2">
          <Row label={language === "ar" ? "رقم الشحنة" : "Shipment No"} value={shipment.shipment_no} />
          <Row label={language === "ar" ? "المورد" : "Supplier"} value={supplierName} />
          <Row label={language === "ar" ? "الوزن المشحون" : "Shipped Weight"} value={`${fmtGrams(Number(shipment.shipped_weight_grams))} g`} />
          <Row label={language === "ar" ? "عدد السبيكات" : "Bar Count"} value={String(shipment.bar_count)} />
          <Row label={language === "ar" ? "الناقل" : "Carrier"} value={shipment.carrier_name ?? "-"} />
          <Row label={language === "ar" ? "رقم التتبع" : "Tracking No"} value={shipment.tracking_no ?? "-"} />
          <Row label={language === "ar" ? "التأمين" : "Insurance"} value={shipment.insurance_provider ?? "-"} />
          <Row label={language === "ar" ? "رقم وثيقة التأمين" : "Policy No"} value={shipment.insurance_policy_no ?? "-"} />
          <Row label={language === "ar" ? "تكلفة الشحن" : "Shipping Cost"} value={fmtMoney(Number(shipment.shipping_cost))} />
          <Row label={language === "ar" ? "الخزنة المستهدفة" : "Target Vault"} value={vault?.name ?? "-"} />
          <Row label={language === "ar" ? "الوصول المتوقع" : "Expected Arrival"} value={shipment.expected_arrival_date ?? "-"} />
          <Row label={language === "ar" ? "تاريخ الإرسال" : "Dispatched At"} value={shipment.dispatched_at ? formatDateTime(shipment.dispatched_at) : "-"} />
          <Row label={language === "ar" ? "تاريخ الوصول" : "Arrived At"} value={shipment.arrived_at ? formatDateTime(shipment.arrived_at) : "-"} />
          {shipment.notes && <div className="sm:col-span-2"><Row label={language === "ar" ? "ملاحظات" : "Notes"} value={shipment.notes} /></div>}
        </div>
      ),
    },
    {
      key: "audit",
      label: { en: "Audit", ar: "التدقيق" },
      content: <AuditHistory entries={auditLogs} language={language} />,
    },
  ]

  return (
    <>
      <EntityDetailPage
        title={shipment.shipment_no}
        description={supplierName}
        breadcrumbs={[
          { label: language === "ar" ? "شحنات الموردين" : "Supplier Shipments", href: "/supplier-shipments" },
          { label: shipment.shipment_no },
        ]}
        status={shipment.status}
        statusLabel={supplierShipmentStatusLabel[shipment.status]}
        statusTone={supplierShipmentStatusTone[shipment.status]}
        workflow={supplierShipmentWorkflow}
        language={language}
        tabs={tabs}
        actions={
          <div className="flex items-center gap-2">
            {shipment.receiving_order_id && (
              <Button onClick={() => router.push(`/warehouse/receiving?order=${shipment.receiving_order_id}`)}>
                <ExternalLink className="h-4 w-4" />
                {language === "ar" ? "فتح أمر الاستلام" : "Open receiving order"}
              </Button>
            )}
            <Button variant="outline" onClick={refresh} disabled={isLoading} title={language === "ar" ? "تحديث" : "Refresh"}>
              <RefreshCw className="h-4 w-4" />
            </Button>
          </div>
        }
        headerExtra={
          <div className="w-full">
            <ActionBar
              definition={supplierShipmentWorkflow}
              status={shipment.status}
              permissions={permissions}
              language={language}
              permissionMap={supplierShipmentPermissionMap}
              onAction={setAction}
              disabled={isSubmitting}
            />
          </div>
        }
      />

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

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>
}
