'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 { useOutboundOrders } from "@/hooks/useLogistics"
import { ActionBar, ActionModal, EntityDetailPage, type DetailTab, type WorkflowAction } from "@/components/workflow"
import { outboundOrderPermissionMap, outboundOrderStatusLabel, outboundOrderStatusTone, outboundOrderWorkflow } from "@/lib/logistics"
import { Button } from "@/components/ui/button"
import { Modal } from "@/components/ui/modal"
import { InputField, TextAreaField } from "@/components/ui/FormFields"
import { fmtGrams, formatDateTime } from "@/lib/format"
import { effectivePermissions } from "@/lib/permissions"

export default function OutboundOrderDetailPage() {
  const { id } = useParams<{ id: string }>()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { selected: order, isLoading, isSubmitting, error, get, act } = useOutboundOrders()
  const [action, setAction] = useState<WorkflowAction | null>(null)
  const [proofModalOpen, setProofModalOpen] = useState(false)
  const [proofUrl, setProofUrl] = useState("")

  const refresh = useCallback(async () => { if (id) await get(id) }, [id, get])
  useEffect(() => { refresh() }, [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 || "Not found"}</div>
  const permissions = effectivePermissions(user)

  const onAction = (a: WorkflowAction) => {
    if (a.key === "confirm_handover") { setProofModalOpen(true); return }
    setAction(a)
  }

  const handleAction = async (reason?: string) => {
    if (!action || !id) return
    try { await act(id, action.key, reason ? { note: reason } : undefined); toast.success("Done"); setAction(null); await refresh() }
    catch (err: any) { toast.error(err?.response?.data?.detail || err?.message) }
  }

  const handleProofSubmit = async () => {
    if (!id || !proofUrl) return
    try { await act(id, "confirm_handover", { proof_of_delivery_url: proofUrl }); toast.success("Proof uploaded"); setProofModalOpen(false); setProofUrl(""); await refresh() }
    catch (err: any) { toast.error(err?.response?.data?.detail || err?.message) }
  }

  const tabs: DetailTab[] = [
    {
      key: "details",
      label: { en: "Details", ar: "تفاصيل" },
      content: (
        <div className="grid gap-3 sm:grid-cols-2">
          <Row label="Order No" value={order.outbound_order_no} />
          <Row label="Source" value={`${order.source_type}: ${order.source_id}`} />
          <Row label="Bars" value={String(order.bar_count)} />
          <Row label="Weight" value={`${fmtGrams(Number(order.total_weight_grams))} g`} />
          <Row label="Carrier" value={order.carrier_name ?? "-"} />
          <Row label="Tracking" value={order.tracking_no ?? "-"} />
          <Row label="Proof" value={order.proof_uploaded ? "Uploaded" : "Not uploaded"} />
          <Row label="Created" value={formatDateTime(order.created_at)} />
          {order.notes && <div className="sm:col-span-2"><Row label="Notes" value={order.notes} /></div>}
        </div>
      ),
    },
  ]

  return (
    <>
      <EntityDetailPage
        title={order.outbound_order_no}
        description={`Source: ${order.source_type}`}
        breadcrumbs={[{ label: language === "ar" ? "أوامر الصرف المخزني" : "Stock Issue Orders", href: "/outbound-orders" }, { label: order.outbound_order_no }]}
        status={order.status}
        statusLabel={outboundOrderStatusLabel[order.status] ?? { en: order.status, ar: order.status }}
        statusTone={outboundOrderStatusTone[order.status] ?? "neutral"}
        workflow={outboundOrderWorkflow}
        language={language}
        tabs={tabs}
        actions={<Button variant="outline" onClick={refresh} disabled={isLoading}><RefreshCw className="h-4 w-4" /></Button>}
        headerExtra={<div className="w-full"><ActionBar definition={outboundOrderWorkflow} status={order.status} permissions={permissions} permissionMap={outboundOrderPermissionMap} language={language} onAction={onAction} disabled={isSubmitting} /></div>}
      />
      <ActionModal open={Boolean(action)} action={action} language={language} entityLabel={order.outbound_order_no} isSubmitting={isSubmitting} onConfirm={handleAction} onClose={() => setAction(null)} />
      <Modal open={proofModalOpen} onClose={() => setProofModalOpen(false)} title="Upload Proof of Delivery" description={order.outbound_order_no} size="sm">
        <div className="space-y-4">
          <InputField id="proof-url" name="proof_of_delivery_url" label="Proof URL" required value={proofUrl} onChange={e => setProofUrl(e.target.value)} />
          <div className="flex justify-end gap-2"><Button variant="outline" onClick={() => setProofModalOpen(false)}>Cancel</Button><Button onClick={handleProofSubmit} isLoading={isSubmitting}>Submit</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>
}
