'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { CheckCircle2, Eye, PackageCheck, Plus, RefreshCw, Send } from "lucide-react"
import { useTranslation } from "react-i18next"
import { useOutboundOrders } from "@/hooks/useLogistics"
import { outboundOrderStatusLabel, outboundOrderStatusTone } from "@/lib/logistics"
import type { OutboundOrder } from "@/types"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { KpiCard } from "@/components/ui/kpi-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"

export default function OutboundOrdersPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { items, total, pages, isLoading, error, list } = useOutboundOrders()
  const [page, setPage] = useState(1)

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

  const metrics = useMemo(() => ({
    active: items.filter(item => ["draft", "approved", "picking", "dispatched"].includes(item.status)).length,
    delivered: items.filter(item => item.status === "delivered").length,
    closed: items.filter(item => item.status === "closed").length,
  }), [items])

  const columns: Column<OutboundOrder>[] = [
    { key: "no", header: language === "ar" ? "رقم الأمر" : "Order No", cell: row => <span className="font-mono font-semibold">{row.outbound_order_no}</span> },
    { key: "source", header: language === "ar" ? "المصدر" : "Source", cell: row => <span>{row.source_type}</span> },
    { key: "bars", header: language === "ar" ? "السبائك" : "Bars", cell: row => <span className="font-mono">{row.bar_count}</span> },
    { key: "weight", header: language === "ar" ? "الوزن" : "Weight", cell: row => <span className="font-mono">{fmtGrams(Number(row.total_weight_grams))} g</span> },
    { key: "status", header: language === "ar" ? "الحالة" : "Status", cell: row => <StatusBadge tone={outboundOrderStatusTone[row.status]}>{outboundOrderStatusLabel[row.status]?.[language] ?? row.status}</StatusBadge> },
    { key: "date", header: language === "ar" ? "تاريخ الإنشاء" : "Created", cell: row => <span className="text-xs">{formatDateTime(row.created_at)}</span> },
    {
      key: "actions",
      header: language === "ar" ? "الإجراء" : "Action",
      align: "end" as const,
      cell: row => (
        <Button size="sm" variant="outline" onClick={event => { event.stopPropagation(); router.push(`/outbound-orders/${row.id}`) }}>
          <Eye className="h-3.5 w-3.5" />
          {language === "ar" ? "عرض" : "View"}
        </Button>
      ),
    },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "أوامر الصرف المخزني" : "Stock Issue Orders"}
        description={language === "ar" ? "إنشاء واعتماد وتجهيز وإرسال وإغلاق أوامر الصرف المخزني." : "Create, approve, pick, dispatch, upload proof, and close stock issue orders."}
        breadcrumbs={[{ label: language === "ar" ? "المخزون" : "Inventory", href: "#" }, { label: language === "ar" ? "أوامر الصرف المخزني" : "Stock Issue Orders" }]}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={refresh} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
            </Button>
            <Button onClick={() => router.push("/outbound-orders/create")}>
              <Plus className="h-4 w-4" />
              {language === "ar" ? "أمر صرف مخزني جديد" : "New stock issue order"}
            </Button>
          </div>
        }
      />

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label={language === "ar" ? "الإجمالي" : "Total"} value={String(total)} icon={PackageCheck} tone="gold" accent />
        <KpiCard label={language === "ar" ? "قيد التنفيذ" : "Active"} value={String(metrics.active)} icon={Send} tone="warning" />
        <KpiCard label={language === "ar" ? "تم التسليم" : "Delivered"} value={String(metrics.delivered)} icon={PackageCheck} tone="info" />
        <KpiCard label={language === "ar" ? "مغلق" : "Closed"} value={String(metrics.closed)} icon={CheckCircle2} tone="success" />
      </div>

      <SectionCard title={language === "ar" ? "أوامر الصرف المخزني" : "Stock issue orders"} 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={row => row.id}
            onRowClick={row => router.push(`/outbound-orders/${row.id}`)}
            empty={<div className="text-center text-sm text-muted-foreground">{language === "ar" ? "لا توجد أوامر صرف مخزني." : "No stock issue orders."}</div>}
          />
        )}
        <Pagination currentPage={page} totalPages={pages} onPageChange={setPage} />
      </SectionCard>
    </div>
  )
}
