'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { Eye, Plus, RefreshCw, Search, Truck, PackageCheck, Clock3, CircleDollarSign } from "lucide-react"
import { useTranslation } from "react-i18next"
import { useAuth } from "@/contexts/auth-context"
import { useSupplierShipments } from "@/hooks/useSupplierShipments"
import { supplierShipmentStatusLabel, supplierShipmentStatusTone } from "@/lib/supplier-shipments"
import type { PaginatedResponse, SupplierDTO, SupplierShipment, SupplierShipmentFilters, VaultDTO } 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"
import { api } from "@/lib/api"

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

export default function SupplierShipmentsPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const { items, total, pages, isLoading, error, list } = useSupplierShipments()
  const [page, setPage] = useState(1)
  const [filters, setFilters] = useState<SupplierShipmentFilters>({ page: 1, page_size: 25 })
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [vaults, setVaults] = useState<VaultDTO[]>([])

  const language = i18n.language.startsWith("ar") ? "ar" : "en"

  useEffect(() => {
    Promise.all([
      api.get("/suppliers/"),
      api.get("/warehouse/vaults"),
    ])
      .then(([s, v]) => {
        setSuppliers(arrayPayload<SupplierDTO>(s))
        setVaults(arrayPayload<VaultDTO>(v))
      })
      .catch(() => undefined)
  }, [])

  const refresh = useCallback(() => list({ ...filters, page }), [filters, list, page])
  useEffect(() => { refresh() }, [refresh])

  const openDetail = useCallback((id: string) => router.push(`/supplier-shipments/${id}`), [router])

  const columns: Column<SupplierShipment>[] = [
    {
      key: "shipment",
      header: language === "ar" ? "رقم الشحنة" : "Shipment",
      cell: row => <span className="font-mono font-semibold">{row.shipment_no}</span>,
    },
    {
      key: "supplier",
      header: language === "ar" ? "المورد" : "Supplier",
      cell: row => {
        const sup = suppliers.find(s => s.id === row.supplier_id)
        return <span>{sup ? (language === "ar" ? sup.name_ar : sup.name_en || sup.name_ar) : "-"}</span>
      },
    },
    {
      key: "carrier",
      header: language === "ar" ? "الناقل" : "Carrier",
      cell: row => <span>{row.carrier_name ?? "-"}</span>,
    },
    {
      key: "weight",
      header: language === "ar" ? "الوزن" : "Weight",
      cell: row => <span className="font-mono">{fmtGrams(Number(row.shipped_weight_grams))}</span>,
    },
    {
      key: "bars",
      header: language === "ar" ? "السبيكات" : "Bars",
      cell: row => <span className="font-mono">{row.bar_count}</span>,
    },
    {
      key: "status",
      header: language === "ar" ? "الحالة" : "Status",
      cell: row => <StatusBadge tone={supplierShipmentStatusTone[row.status]}>{supplierShipmentStatusLabel[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",
      cell: row => (
        <div className="flex justify-end gap-2" onClick={e => e.stopPropagation()}>
          <Button size="sm" variant="outline" onClick={() => openDetail(row.id)}>
            <Eye className="h-3.5 w-3.5" />
            {language === "ar" ? "عرض" : "View"}
          </Button>
        </div>
      ),
    },
  ]

  const inTransit = useMemo(() => items.filter(i => ["dispatched", "in_transit"].includes(i.status)).length, [items])
  const arrived = useMemo(() => items.filter(i => i.status === "arrived").length, [items])
  const closed = useMemo(() => items.filter(i => i.status === "closed").length, [items])

  const setFilter = (key: keyof SupplierShipmentFilters, value: string) => {
    setPage(1)
    setFilters(current => ({ ...current, [key]: value || undefined }))
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "شحنات الموردين" : "Supplier Shipments"}
        description={language === "ar" ? "تتبع شحنات الذهب من الموردين حتى الاستلام." : "Track gold shipments from suppliers until receiving."}
        breadcrumbs={[
          { label: language === "ar" ? "المخزون واللوجستيات" : "Inventory & Logistics", href: "#" },
          { label: language === "ar" ? "شحنات الموردين" : "Supplier Shipments" },
        ]}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={refresh} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
            </Button>
            {(user?.permissions?.includes("warehouse:delivery_create") || user?.role === "super_admin" || user?.roles?.some(r => r.code === "super_admin")) && (
              <Button onClick={() => router.push("/supplier-shipments/create")}>
                <Plus className="h-4 w-4" />
                {language === "ar" ? "شحنة جديدة" : "New shipment"}
              </Button>
            )}
          </div>
        }
      />

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label={language === "ar" ? "إجمالي الشحنات" : "Total shipments"} value={String(total)} icon={Truck} tone="gold" accent />
        <KpiCard label={language === "ar" ? "قيد النقل" : "In transit"} value={String(inTransit)} icon={Clock3} tone="warning" />
        <KpiCard label={language === "ar" ? "وصلت" : "Arrived"} value={String(arrived)} icon={PackageCheck} tone="info" />
        <KpiCard label={language === "ar" ? "مغلقة" : "Closed"} value={String(closed)} icon={CircleDollarSign} tone="success" />
      </div>

      <SectionCard title={language === "ar" ? "البحث والتصفية" : "Search and filters"}>
        <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-5">
          <label className="relative xl:col-span-2">
            <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <input
              className="w-full rounded-lg border border-border bg-background py-2.5 pl-9 pr-3 text-sm"
              placeholder={language === "ar" ? "رقم الشحنة" : "Shipment number"}
              value={filters.search ?? ""}
              onChange={e => setFilter("search", e.target.value)}
            />
          </label>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.status_filter ?? ""} onChange={e => setFilter("status_filter", e.target.value)}>
            <option value="">{language === "ar" ? "كل الحالات" : "All statuses"}</option>
            {Object.entries(supplierShipmentStatusLabel).map(([value, label]) => <option key={value} value={value}>{label[language]}</option>)}
          </select>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.supplier_id ?? ""} onChange={e => setFilter("supplier_id", e.target.value)}>
            <option value="">{language === "ar" ? "كل الموردين" : "All suppliers"}</option>
            {suppliers.map(s => <option key={s.id} value={s.id}>{language === "ar" ? s.name_ar : s.name_en || s.name_ar}</option>)}
          </select>
        </div>
      </SectionCard>

      <SectionCard title={language === "ar" ? "قائمة الشحنات" : "Shipments"} 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 => openDetail(row.id)}
            ariaLabel="Supplier shipments"
            empty={<div className="text-center text-sm text-muted-foreground">{language === "ar" ? "لا توجد شحنات." : "No shipments."}</div>}
          />
        )}
        <Pagination currentPage={page} totalPages={pages} onPageChange={setPage} />
      </SectionCard>
    </div>
  )
}