'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 { usePlatformAllocations } from "@/hooks/useLogistics"
import { ActionBar, ActionModal, EntityDetailPage, type DetailTab, type WorkflowAction } from "@/components/workflow"
import { platformAllocationStatusLabel, platformAllocationStatusTone, platformAllocationWorkflow } from "@/lib/logistics"
import { Button } from "@/components/ui/button"
import { fmtGrams, formatDateTime } from "@/lib/format"

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

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

  if (isLoading && !alloc) 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 (!alloc) 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); 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="Allocation No" value={alloc.allocation_no} />
          <Row label="Sale Channel" value={alloc.sale_channel ?? "-"} />
          <Row label="Bars" value={String(alloc.bar_count)} />
          <Row label="Weight" value={`${fmtGrams(Number(alloc.total_weight_grams))} g`} />
          <Row label="Source Vault" value={alloc.source_vault_id ?? "INV-STORE"} />
          <Row label="Target Vault" value={alloc.target_vault_id ?? "INV-PLATFORM"} />
          <Row label="Created" value={formatDateTime(alloc.created_at)} />
          {alloc.notes && <div className="sm:col-span-2"><Row label="Notes" value={alloc.notes} /></div>}
        </div>
      ),
    },
  ]

  return (
    <>
      <EntityDetailPage
        title={alloc.allocation_no}
        description={alloc.sale_channel ?? ""}
        breadcrumbs={[{ label: "Platform Allocations", href: "/platform-allocations" }, { label: alloc.allocation_no }]}
        status={alloc.status}
        statusLabel={platformAllocationStatusLabel[alloc.status] ?? { en: alloc.status, ar: alloc.status }}
        statusTone={platformAllocationStatusTone[alloc.status] ?? "neutral"}
        workflow={platformAllocationWorkflow}
        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={platformAllocationWorkflow} status={alloc.status} permissions={user?.permissions ?? []} language={language} onAction={setAction} disabled={isSubmitting} /></div>}
      />
      <ActionModal open={Boolean(action)} action={action} language={language} entityLabel={alloc.allocation_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>
}