'use client'

import { useCallback, useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Eye, Plus, RefreshCw, RotateCcw } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { usePurchaseReturns } from "@/hooks/useLogistics"
import { purchaseReturnStatusLabel, purchaseReturnStatusTone } from "@/lib/logistics"
import type { PurchaseReturn, SupplierDTO } 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, fmtMoney, formatDateTime } from "@/lib/format"
import { api } from "@/lib/api"
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 PurchaseReturnsPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { items, total, pages, isLoading, error, list, create, isSubmitting } = usePurchaseReturns()
  const [page, setPage] = useState(1)
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [createOpen, setCreateOpen] = useState(false)
  const [form, setForm] = useState({ supplier_id: "", source_inventory: "INV-INSPECTION", reason: "", notes: "" })

  useEffect(() => { api.get("/suppliers/").then(s => setSuppliers(arrayPayload<SupplierDTO>(s))).catch(() => {}) }, [])

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

  const columns: Column<PurchaseReturn>[] = [
    { key: "no", header: "Return No", cell: r => <span className="font-mono font-semibold">{r.return_no}</span> },
    { key: "source", header: "Source", cell: r => <span>{r.source_inventory}</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: "value", header: "Value", cell: r => <span className="font-mono">{fmtMoney(Number(r.total_value))}</span> },
    { key: "status", header: "Status", cell: r => <StatusBadge tone={purchaseReturnStatusTone[r.status]}>{purchaseReturnStatusLabel[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(`/purchase-returns/${r.id}`) }}><Eye className="h-3.5 w-3.5" />View</Button> },
  ]

  const handleCreate = async () => {
    try {
      const ret = await create({ supplier_id: form.supplier_id || undefined, source_inventory: form.source_inventory, reason: form.reason, notes: form.notes })
      toast.success("Return created"); setCreateOpen(false); router.push(`/purchase-returns/${ret.id}`)
    } catch (err: any) { toast.error(err?.response?.data?.detail || err?.message) }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "مرتجعات الشراء" : "Purchase Returns"}
        description={language === "ar" ? "إدارة مرتجعات الذهب للموردين." : "Manage gold purchase returns to suppliers."}
        breadcrumbs={[{ label: "Inventory", href: "#" }, { label: "Purchase Returns" }]}
        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 Return</Button></div>}
      />
      <SectionCard title="Purchase returns" 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(`/purchase-returns/${r.id}`)} empty={<div className="text-center text-sm text-muted-foreground">No returns.</div>} />
        )}
        <Pagination currentPage={page} totalPages={pages} onPageChange={setPage} />
      </SectionCard>
    </div>
  )
}