'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 { usePurchaseReturns } from "@/hooks/useLogistics"
import { ActionBar, ActionModal, EntityDetailPage, type DetailTab, type WorkflowAction } from "@/components/workflow"
import { purchaseReturnStatusLabel, purchaseReturnStatusTone, purchaseReturnWorkflow } from "@/lib/logistics"
import { Button } from "@/components/ui/button"
import { fmtGrams, fmtMoney, formatDateTime } from "@/lib/format"

export default function PurchaseReturnDetailPage() {
  const { id } = useParams<{ id: string }>()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { selected: ret, isLoading, isSubmitting, error, get, act } = usePurchaseReturns()
  const [action, setAction] = useState<WorkflowAction | null>(null)

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

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

  const handleAction = async (reason?: string) => {
    if (!action || !id) return
    try { await act(id, action.key, reason); toast.success("Done"); setAction(null); 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="Return No" value={ret.return_no} />
          <Row label="Source" value={ret.source_inventory} />
          <Row label="Bars" value={String(ret.bar_count)} />
          <Row label="Weight" value={`${fmtGrams(Number(ret.total_weight_grams))} g`} />
          <Row label="Value" value={fmtMoney(Number(ret.total_value))} />
          <Row label="Created" value={formatDateTime(ret.created_at)} />
          {ret.reason && <div className="sm:col-span-2"><Row label="Reason" value={ret.reason} /></div>}
          {ret.notes && <div className="sm:col-span-2"><Row label="Notes" value={ret.notes} /></div>}
        </div>
      ),
    },
  ]

  return (
    <>
      <EntityDetailPage
        title={ret.return_no}
        description={ret.source_inventory}
        breadcrumbs={[{ label: "Purchase Returns", href: "/purchase-returns" }, { label: ret.return_no }]}
        status={ret.status}
        statusLabel={purchaseReturnStatusLabel[ret.status] ?? { en: ret.status, ar: ret.status }}
        statusTone={purchaseReturnStatusTone[ret.status] ?? "neutral"}
        workflow={purchaseReturnWorkflow}
        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={purchaseReturnWorkflow} status={ret.status} permissions={user?.permissions ?? []} language={language} onAction={setAction} disabled={isSubmitting} /></div>}
      />
      <ActionModal open={Boolean(action)} action={action} language={language} entityLabel={ret.return_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>
}