'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { Eye, Plus, RefreshCw, Search, ShoppingBag, CircleDollarSign, Clock3 } from "lucide-react"
import { useTranslation } from "react-i18next"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import { useAuth } from "@/contexts/auth-context"
import { useSellOrders } from "@/hooks/useSellOrders"
import { allowedSellActions, displayCustomer, sellStatusLabel, sellStatusTone } from "@/lib/sell-orders"
import type { BranchDTO, CurrencyOption, PaginatedResponse, PuritySummary, SellOrderFilters, SellOrderListItem, 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 { fmtMoney, formatDateTime } from "@/lib/format"

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

const nextActionLabel: Record<string, { en: string; ar: string }> = {
  submit: { en: "Review", ar: "مراجعة" },
  review: { en: "Approve", ar: "اعتماد" },
  approve: { en: "Approve", ar: "اعتماد" },
  cancel: { en: "Cancel", ar: "إلغاء" },
}

export default function SellOrdersPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const { user } = useAuth()
  const { items, total, pages, isLoading, error, list } = useSellOrders()
  const [page, setPage] = useState(1)
  const [filters, setFilters] = useState<SellOrderFilters>({ page: 1, page_size: 25 })
  const [branches, setBranches] = useState<BranchDTO[]>([])
  const [vaults, setVaults] = useState<VaultDTO[]>([])
  const [purities, setPurities] = useState<PuritySummary[]>([])
  const [currencies, setCurrencies] = useState<CurrencyOption[]>([])
  const [filtersLoading, setFiltersLoading] = useState(true)

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

  useEffect(() => {
    setFiltersLoading(true)
    Promise.all([
      api.get("/branches/"),
      api.get("/warehouse/vaults"),
      api.get("/purities/", { params: { active_only: true } }),
      api.get(ENDPOINTS.CURRENCIES.LIST),
    ])
      .then(([b, v, p, c]) => {
        setBranches(arrayPayload<BranchDTO>(b))
        setVaults(arrayPayload<VaultDTO>(v))
        setPurities(arrayPayload<PuritySummary>(p))
        setCurrencies(Array.isArray(c?.data ?? c) ? (c?.data ?? c) : [])
      })
      .catch(() => undefined)
      .finally(() => setFiltersLoading(false))
  }, [])

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

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

  const columns: Column<SellOrderListItem>[] = [
    {
      key: "order",
      header: language === "ar" ? "رقم الأمر" : "Order",
      cell: row => <span className="font-mono font-semibold">{row.sell_order_no}</span>,
    },
    {
      key: "customer",
      header: language === "ar" ? "العميل" : "Customer",
      cell: row => (
        <div>
          <p className="font-medium">{displayCustomer(row.customer, language)}</p>
          <p className="text-[11px] text-muted-foreground">{row.customer?.customer_code || "-"}</p>
        </div>
      ),
    },
    {
      key: "branch",
      header: language === "ar" ? "الفرع / الخزنة" : "Branch / Vault",
      cell: row => (
        <div>
          <p>{(language === "ar" ? row.branch?.name_ar : row.branch?.name_en) || "-"}</p>
          <p className="text-[11px] text-muted-foreground">{row.vault?.name || "-"}</p>
        </div>
      ),
    },
    {
      key: "amount",
      header: language === "ar" ? "الإجمالي" : "Total",
      cell: row => <span className="font-mono font-semibold">{fmtMoney(Number(row.total_amount), row.currency?.code ?? undefined)}</span>,
    },
    {
      key: "status",
      header: language === "ar" ? "الحالة" : "Status",
      cell: row => <StatusBadge tone={sellStatusTone[row.status]}>{sellStatusLabel[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 => {
        const actions = allowedSellActions(row.status, user?.permissions ?? [])
        const primary = actions.find(action => ["submit", "review", "approve", "cancel"].includes(action))
        return (
          <div className="flex justify-end gap-2" onClick={event => event.stopPropagation()}>
            <Button size="sm" variant="outline" onClick={() => openDetail(row.id)}>
              <Eye className="h-3.5 w-3.5" />
              {language === "ar" ? "عرض" : "View"}
            </Button>
            {primary && (
              <Button size="sm" variant={primary === "cancel" ? "danger" : "primary"} onClick={() => openDetail(row.id)}>
                {nextActionLabel[primary]?.[language] ?? primary}
              </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 posted = useMemo(() => items.filter(item => item.status === "posted").length, [items])

  const setFilter = (key: keyof SellOrderFilters, value: string) => {
    setPage(1)
    setFilters(current => {
      const next = { ...current, [key]: value || undefined }
      if (key === "branch_id") next.vault_id = undefined
      return next
    })
  }

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

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "أوامر بيع الذهب" : "Sell Gold Orders"}
        description={language === "ar" ? "إنشاء ومراجعة واعتماد وترحيل عمليات بيع الذهب." : "Create, review, approve, and post gold sell orders."}
        breadcrumbs={[
          { label: language === "ar" ? "العمليات المالية" : "Financial operations", href: "#" },
          { label: language === "ar" ? "أوامر البيع" : "Sell orders" },
        ]}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={refresh} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
            </Button>
            {user?.permissions?.includes("sell_orders:create") && (
              <Button onClick={() => router.push("/sell-orders/create")}>
                <Plus className="h-4 w-4" />
                {language === "ar" ? "أمر بيع جديد" : "New sell 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" ? "الأوامر المرحلة" : "Posted orders"} value={String(posted)} icon={CircleDollarSign} tone="info" />
      </div>

      <SectionCard title={language === "ar" ? "البحث والتصفية" : "Search and filters"}>
        <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-9">
          <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 or customer"}
              value={filters.search ?? ""}
              onChange={event => setFilter("search", event.target.value)}
            />
          </label>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.status ?? ""} onChange={event => setFilter("status", event.target.value)}>
            <option value="">{language === "ar" ? "كل الحالات" : "All statuses"}</option>
            {Object.entries(sellStatusLabel).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.branch_id ?? ""} onChange={event => setFilter("branch_id", event.target.value)} disabled={filtersLoading}>
            <option value="">{language === "ar" ? "كل الفروع" : "All branches"}</option>
            {branches.map(branch => <option key={branch.id} value={branch.id}>{language === "ar" ? branch.name_ar : branch.name_en || branch.name_ar}</option>)}
          </select>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.vault_id ?? ""} onChange={event => setFilter("vault_id", event.target.value)} disabled={filtersLoading}>
            <option value="">{language === "ar" ? "كل الخزن" : "All vaults"}</option>
            {vaults.filter(vault => !filters.branch_id || vault.branch_id === filters.branch_id).map(vault => <option key={vault.id} value={vault.id}>{vault.name}</option>)}
          </select>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.purity_id ?? ""} onChange={event => setFilter("purity_id", event.target.value)} disabled={filtersLoading}>
            <option value="">{language === "ar" ? "كل العيارات" : "All purities"}</option>
            {purities.map(purity => <option key={purity.id} value={purity.id}>{purity.karat}K</option>)}
          </select>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.currency_id ?? ""} onChange={event => setFilter("currency_id", event.target.value)} disabled={filtersLoading}>
            <option value="">{language === "ar" ? "كل العملات" : "All currencies"}</option>
            {currencies.map(currency => <option key={currency.id} value={currency.id}>{currency.code} - {language === "ar" ? currency.name_ar : currency.name_en}</option>)}
          </select>
          <input type="date" className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.date_from ?? ""} onChange={event => setFilter("date_from", event.target.value)} />
          <input type="date" className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.date_to ?? ""} onChange={event => setFilter("date_to", event.target.value)} />
        </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" ? "قائمة أوامر البيع" : "Sell 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="Sell orders"
            empty={<div className="text-center text-sm text-muted-foreground">{language === "ar" ? "لا توجد أوامر بيع مطابقة." : "No matching sell orders."}</div>}
          />
        )}
        <Pagination currentPage={page} totalPages={pages} onPageChange={setPage} />
      </SectionCard>
    </div>
  )
}
