'use client'

import { useCallback, useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Eye, Plus, RefreshCw, Boxes } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { usePlatformAllocations } from "@/hooks/useLogistics"
import { platformAllocationStatusLabel, platformAllocationStatusTone } from "@/lib/logistics"
import type { PlatformAllocation, VaultDTO } from "@/types"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge } from "@/components/ui/status-badge"
import { Button } from "@/components/ui/button"
import { Pagination } from "@/components/ui/Pagination"
import { fmtGrams, formatDateTime } from "@/lib/format"
import { api } from "@/lib/api"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField, TextAreaField } from "@/components/ui/FormFields"
import type { PaginatedResponse } from "@/types"

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

export default function PlatformAllocationsPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { items, total, pages, isLoading, error, list, create, isSubmitting } = usePlatformAllocations()
  const [page, setPage] = useState(1)
  const [vaults, setVaults] = useState<VaultDTO[]>([])
  const [createOpen, setCreateOpen] = useState(false)
  const [form, setForm] = useState({ source_vault_id: "", target_vault_id: "", sale_channel: "", bar_count: "", total_weight_grams: "", notes: "" })

  useEffect(() => { api.get("/warehouse/vaults").then(v => setVaults(arrayPayload<VaultDTO>(v))).catch(() => {}) }, [])

  const refresh = useCallback(() => list({ page, page_size: 25 }), [list, page])
  useEffect(() => { refresh() }, [refresh])

  const columns: Column<PlatformAllocation>[] = [
    { key: "no", header: "Allocation No", cell: r => <span className="font-mono font-semibold">{r.allocation_no}</span> },
    { key: "channel", header: "Channel", cell: r => <span>{r.sale_channel ?? "-"}</span> },
    { key: "bars", header: "Bars", cell: r => <span className="font-mono">{r.bar_count}</span> },
    { key: "weight", header: "Weight", cell: r => <span className="font-mono">{fmtGrams(Number(r.total_weight_grams))} g</span> },
    { key: "status", header: "Status", cell: r => <StatusBadge tone={platformAllocationStatusTone[r.status]}>{platformAllocationStatusLabel[r.status]?.[language] ?? r.status}</StatusBadge> },
    { key: "date", header: "Created", cell: r => <span className="text-xs">{formatDateTime(r.created_at)}</span> },
    { key: "actions", header: "Action", align: "end" as const, cell: r => <Button size="sm" variant="outline" onClick={e => { e.stopPropagation(); router.push(`/platform-allocations/${r.id}`) }}><Eye className="h-3.5 w-3.5" />View</Button> },
  ]

  const handleCreate = async () => {
    try {
      const alloc = await create({
        source_vault_id: form.source_vault_id || undefined,
        target_vault_id: form.target_vault_id || undefined,
        sale_channel: form.sale_channel || undefined,
        bar_count: Number(form.bar_count) || 0,
        total_weight_grams: Number(form.total_weight_grams) || 0,
        notes: form.notes || undefined,
      })
      toast.success("Allocation created"); setCreateOpen(false); router.push(`/platform-allocations/${alloc.id}`)
    } catch (err: any) { toast.error(err?.response?.data?.detail || err?.message) }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "تخصيص المنصة" : "Platform Allocations"}
        description={language === "ar" ? "نقل السبيكات من INV-STORE إلى INV-PLATFORM للتداول." : "Transfer bars from INV-STORE to INV-PLATFORM for trading."}
        breadcrumbs={[{ label: "Inventory", href: "#" }, { label: "Platform Allocations" }]}
        actions={<div className="flex gap-2"><Button variant="outline" onClick={refresh} disabled={isLoading}><RefreshCw className="h-4 w-4" /></Button><Button onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4" />New Allocation</Button></div>}
      />
      <SectionCard title="Allocations" padded={false}>
        {error && <div className="m-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">{error}</div>}
        {isLoading ? <div className="flex h-52 items-center justify-center"><div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" /></div> : (
          <DataTable columns={columns} data={items} rowKey={r => r.id} onRowClick={r => router.push(`/platform-allocations/${r.id}`)} empty={<div className="text-center text-sm text-muted-foreground">No allocations.</div>} />
        )}
        <Pagination currentPage={page} totalPages={pages} onPageChange={setPage} />
      </SectionCard>

      <Modal open={createOpen} onClose={() => setCreateOpen(false)} title="Create Platform Allocation" size="md">
        <div className="grid gap-4 sm:grid-cols-2">
          <SelectField id="source-vault" name="source_vault_id" label="Source Vault (INV-STORE)" value={form.source_vault_id} onChange={e => setForm(f => ({ ...f, source_vault_id: e.target.value }))} options={vaults.map(v => ({ value: v.id, label: v.name }))} />
          <SelectField id="target-vault" name="target_vault_id" label="Target Vault (INV-PLATFORM)" value={form.target_vault_id} onChange={e => setForm(f => ({ ...f, target_vault_id: e.target.value }))} options={vaults.map(v => ({ value: v.id, label: v.name }))} />
          <InputField id="channel" name="sale_channel" label="Sale Channel" value={form.sale_channel} onChange={e => setForm(f => ({ ...f, sale_channel: e.target.value }))} />
          <InputField id="bars" name="bar_count" label="Bar Count" type="number" min="0" value={form.bar_count} onChange={e => setForm(f => ({ ...f, bar_count: e.target.value }))} />
          <InputField id="weight" name="total_weight_grams" label="Total Weight (g)" type="number" min="0" step="0.000001" value={form.total_weight_grams} onChange={e => setForm(f => ({ ...f, total_weight_grams: e.target.value }))} />
          <div className="sm:col-span-2"><TextAreaField id="notes" name="notes" label="Notes" rows={2} value={form.notes} onChange={e => setForm(f => ({ ...f, notes: e.target.value }))} /></div>
        </div>
        <div className="mt-4 flex justify-end gap-2"><Button variant="outline" onClick={() => setCreateOpen(false)}>Cancel</Button><Button onClick={handleCreate} isLoading={isSubmitting}>Create</Button></div>
      </Modal>
    </div>
  )
}