'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { ArrowDownToLine, Eye, Plus, RefreshCw, Search, ShoppingBag, CircleDollarSign, Clock3 } from "lucide-react"
import { useTranslation } from "react-i18next"
import { usePurchaseOrders } from "@/hooks/usePurchaseOrders"
import { purchaseOrderStatusLabel, purchaseOrderStatusTone } from "@/lib/purchase-orders"
import type { BranchDTO, CurrencyOption, PaginatedResponse, PurchaseOrderFilters, PurchaseOrder, SupplierDTO } 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 { fmtMoney, formatDateTime } from "@/lib/format"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"

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

export default function PurchaseOrdersPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const { items, total, pages, isLoading, error, list } = usePurchaseOrders()
  const [page, setPage] = useState(1)
  const [filters, setFilters] = useState<PurchaseOrderFilters>({ page: 1, page_size: 25 })
  const [branches, setBranches] = useState<BranchDTO[]>([])
  const [currencies, setCurrencies] = useState<CurrencyOption[]>([])
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [filtersLoading, setFiltersLoading] = useState(true)

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

  useEffect(() => {
    setFiltersLoading(true)
    Promise.all([
      api.get("/branches/"),
      api.get(ENDPOINTS.CURRENCIES.LIST),
      api.get("/suppliers/"),
    ])
      .then(([b, c, s]) => {
        setBranches(arrayPayload<BranchDTO>(b))
        setCurrencies(Array.isArray(c?.data ?? c) ? (c?.data ?? c) : [])
        setSuppliers(arrayPayload<SupplierDTO>(s))
      })
      .catch(() => undefined)
      .finally(() => setFiltersLoading(false))
  }, [])

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

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

  const columns: Column<PurchaseOrder>[] = [
    {
      key: "order",
      header: language === "ar" ? "رقم الأمر" : "Order",
      cell: row => <span className="font-mono font-semibold">{row.buy_order_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) : row.supplier_reference ?? "-"}</span>
      },
    },
    {
      key: "branch",
      header: language === "ar" ? "الفرع" : "Branch",
      cell: row => {
        const branch = branches.find(b => b.id === row.target_branch_id)
        return <span>{(language === "ar" ? branch?.name_ar : branch?.name_en) ?? "-"}</span>
      },
    },
    {
      key: "amount",
      header: language === "ar" ? "الإجمالي" : "Total",
      cell: row => {
        const cur = currencies.find(c => c.id === row.currency_id)
        return <span className="font-mono font-semibold">{fmtMoney(Number(row.total_amount), cur?.code)}</span>
      },
    },
    {
      key: "status",
      header: language === "ar" ? "الحالة" : "Status",
      cell: row => <StatusBadge tone={purchaseOrderStatusTone[row.status]}>{purchaseOrderStatusLabel[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 totalValue = useMemo(() => items.reduce((sum, item) => sum + Number(item.total_amount || 0), 0), [items])
  const pending = useMemo(() => items.filter(item => ["pending_review", "pending_approval", "approved"].includes(item.status)).length, [items])
  const closed = useMemo(() => items.filter(item => item.status === "closed" || item.status === "fully_supplied").length, [items])

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

  const clearFilters = () => {
    setPage(1)
    setFilters({ page: 1, page_size: 25 })
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "أوامر الشراء" : "Purchase Orders"}
        description={language === "ar" ? "إنشاء ومراجعة واعتماد وإرسال أوامر شراء الذهب للموردين." : "Create, review, approve, and send gold purchase orders to suppliers."}
        breadcrumbs={[
          { label: language === "ar" ? "المخزون واللوجستيات" : "Inventory & Logistics", href: "#" },
          { label: language === "ar" ? "أوامر الشراء" : "Purchase 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("/purchase-orders/create")}>
              <Plus className="h-4 w-4" />
              {language === "ar" ? "أمر شراء جديد" : "New purchase order"}
            </Button>
          </div>
        }
      />

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label={language === "ar" ? "إجمالي الأوامر" : "Total orders"} value={String(total)} icon={ShoppingBag} tone="gold" accent />
        <KpiCard label={language === "ar" ? "قيد الإجراء" : "Pending action"} value={String(pending)} icon={Clock3} tone="warning" />
        <KpiCard label={language === "ar" ? "قيمة الصفحة" : "Page value"} value={fmtMoney(totalValue)} icon={CircleDollarSign} tone="success" />
        <KpiCard label={language === "ar" ? "مكتملة" : "Completed"} value={String(closed)} icon={ArrowDownToLine} tone="info" />
      </div>

      <SectionCard title={language === "ar" ? "البحث والتصفية" : "Search and filters"}>
        <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-7">
          <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" ? "رقم الأمر" : "Order 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(purchaseOrderStatusLabel).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)} disabled={filtersLoading}>
            <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>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.branch_id ?? ""} onChange={e => setFilter("branch_id", e.target.value)} disabled={filtersLoading}>
            <option value="">{language === "ar" ? "كل الفروع" : "All branches"}</option>
            {branches.map(b => <option key={b.id} value={b.id}>{language === "ar" ? b.name_ar : b.name_en || b.name_ar}</option>)}
          </select>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.currency_id ?? ""} onChange={e => setFilter("currency_id", e.target.value)} disabled={filtersLoading}>
            <option value="">{language === "ar" ? "كل العملات" : "All currencies"}</option>
            {currencies.map(c => <option key={c.id} value={c.id}>{c.code}</option>)}
          </select>
        </div>
        <div className="mt-3 flex justify-end">
          <Button size="sm" variant="ghost" onClick={clearFilters}>{language === "ar" ? "مسح الفلاتر" : "Clear filters"}</Button>
        </div>
      </SectionCard>

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