'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 { useAuth } from "@/contexts/auth-context"
import { useBuyOrders } from "@/hooks/useBuyOrders"
import { allowedBuyActions, buyStatusLabel, buyStatusTone, buyTypeLabel, buyWorkflowPermissionsForUser, partyLabel } from "@/lib/buy-orders"
import type { BuyOrderFilters, BuyOrderListItem, BuyOrderStatus, BranchDTO, CurrencyOption, PaginatedResponse, 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"
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 ?? []
}

const primaryActionLabel: Record<string, { en: string; ar: string }> = {
  submit: { en: "Review", ar: "مراجعة" },
  review: { en: "Approve", ar: "اعتماد" },
  approve: { en: "Approve", ar: "اعتماد" },
  post: { en: "Post", ar: "ترحيل" },
  send: { en: "Send", ar: "إرسال" },
  partial: { en: "Partial", ar: "جزئي" },
  full: { en: "Full", ar: "كامل" },
  close: { en: "Close", ar: "إغلاق" },
  "post-buyback": { en: "Post buyback", ar: "ترحيل الشراء" },
}

function canCreateBuyOrder(user: ReturnType<typeof useAuth>["user"]) {
  if (!user) return false
  const permissions = new Set(user.permissions || [])
  const roles = new Set([
    user.role,
    ...(user.roles || []).map((role) => role.code),
  ].filter(Boolean))
  return (
    permissions.has("buy_orders:create") ||
    user.user_type === "admin" ||
    roles.has("super_admin") ||
    roles.has("operations_manager") ||
    roles.has("finance_admin") ||
    roles.has("warehouse_manager")
  )
}

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

  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const canCreate = canCreateBuyOrder(user)
  const workflowPermissions = useMemo(() => buyWorkflowPermissionsForUser(user), [user])

  useEffect(() => {
    setFiltersLoading(true)
    Promise.all([
      api.get("/branches/"),
      api.get("/warehouse/vaults"),
      api.get(ENDPOINTS.CURRENCIES.LIST),
    ])
      .then(([b, v, c]) => {
        setBranches(arrayPayload<BranchDTO>(b))
        setVaults(arrayPayload<VaultDTO>(v))
        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(`/buy-orders/${id}`), [router])

  const columns: Column<BuyOrderListItem>[] = [
    {
      key: "order",
      header: language === "ar" ? "رقم الأمر" : "Order",
      cell: row => <span className="font-mono font-semibold">{row.buy_order_no}</span>,
    },
    {
      key: "type",
      header: language === "ar" ? "النوع" : "Type",
      cell: row => <span>{buyTypeLabel[row.buy_order_type]?.[language] ?? row.buy_order_type}</span>,
    },
    {
      key: "party",
      header: language === "ar" ? "الطرف" : "Party",
      cell: row => <span className="text-[13px]">{partyLabel(row, language)}</span>,
    },
    {
      key: "target",
      header: language === "ar" ? "الفرع / الخزنة" : "Branch / Vault",
      cell: row => (
        <div>
          <p>{(language === "ar" ? row.target_branch?.name_ar : row.target_branch?.name_en) || row.target_branch_id || "-"}</p>
          <p className="text-[11px] text-muted-foreground">{row.target_vault?.name || row.target_vault_id || "-"}</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={buyStatusTone[row.status as BuyOrderStatus] ?? "neutral"}>
          {buyStatusLabel[row.status as BuyOrderStatus]?.[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 = allowedBuyActions(row.status as BuyOrderStatus, workflowPermissions, row.buy_order_type)
        const primary = actions.find(action => ["submit", "review", "approve", "post", "send", "partial", "full", "close", "post-buyback"].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" onClick={() => openDetail(row.id)}>
                {primaryActionLabel[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", "posted", "sent_to_supplier", "partially_supplied"].includes(item.status)).length, [items])
  const posted = useMemo(() => items.filter(item => item.status === "posted" || item.status === "closed").length, [items])

  const setFilter = (key: keyof BuyOrderFilters, 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" ? "أوامر شراء الذهب" : "Buy Gold Orders"}
        description={language === "ar" ? "إنشاء ومراجعة واعتماد وترحيل عمليات شراء الذهب." : "Create, review, approve, post, and receive gold purchase orders."}
        breadcrumbs={[
          { label: language === "ar" ? "العمليات المالية" : "Financial operations", href: "#" },
          { label: language === "ar" ? "أوامر الشراء" : "Buy orders" },
        ]}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={refresh} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
            </Button>
            {canCreate && (
              <Button onClick={() => router.push("/buy-orders/create")}>
                <Plus className="h-4 w-4" />
                {language === "ar" ? "أمر شراء جديد" : "New buy 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 / closed"} value={String(posted)} icon={ArrowDownToLine} tone="info" />
      </div>

      <SectionCard title={language === "ar" ? "البحث والتصفية" : "Search and filters"}>
        <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-8">
          <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 reference"}
              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(buyStatusLabel).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.buy_order_type ?? ""} onChange={event => setFilter("buy_order_type", event.target.value)}>
            <option value="">{language === "ar" ? "كل الأنواع" : "All types"}</option>
            {Object.entries(buyTypeLabel).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.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)} />
        </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" ? "قائمة أوامر الشراء" : "Buy 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="Buy orders"
            empty={<div className="text-center text-sm text-muted-foreground">{language === "ar" ? "لا توجد أوامر شراء مطابقة." : "No matching buy orders."}</div>}
          />
        )}
        <Pagination currentPage={page} totalPages={pages} onPageChange={setPage} />
      </SectionCard>
    </div>
  )
}

