'use client'

import { useEffect, useMemo, useState } from "react"
import { useSearchParams } from "next/navigation"
import {
  AlertTriangle,
  ArrowDownUp,
  BarChart3,
  Coins,
  Download,
  FileSpreadsheet,
  FileText,
  Landmark,
  Search,
  UserRound,
  Wallet,
} from "lucide-react"

import { InputField, SelectField } from "@/components/ui/FormFields"
import {
  printReportPdf,
  type ReportPdfFilter,
  type ReportPdfMetric,
  type ReportPdfRow,
} from "@/components/reports/report-pdf"
import { KpiCard } from "@/components/ui/kpi-card"
import { PageHeader } from "@/components/ui/page-header"
import { SearchableSelectField, type SearchableSelectOption } from "@/components/ui/searchable-select-field"
import { SectionCard } from "@/components/ui/section-card"
import { ENDPOINTS } from "@/constants/endpoints"
import { useBranches } from "@/hooks/useBranches"
import { useCustomers } from "@/hooks/useCustomers"
import { useReports, type ReportExportFormat, type ReportPayload } from "@/hooks/useReports"
import { useVaults } from "@/hooks/useVaults"
import { formatDateTime, formatGold, formatMoney, formatNumber } from "@/lib/format"
import i18n from "@/lib/i18n"

type Lang = "ar" | "en"
type ReportCode =
  | "general_ledger"
  | "trial_balance"
  | "customer_statement"
  | "gold_balance"
  | "gold_movement"
  | "vault_balance"
  | "fees_profit"

type ReportConfig = {
  code: ReportCode
  category: "accounting" | "gold" | "revenue"
  title: Record<Lang, string>
  description: Record<Lang, string>
  endpoint: string | ((customerId: string) => string)
  icon: typeof Landmark
  requires: string[]
  defaultFilters: Partial<ReportFilters>
  columns: ColumnConfig[]
  summary: SummaryConfig[]
}

type ColumnConfig = {
  key: string
  label: Record<Lang, string>
  format?: "money" | "gold" | "number" | "date" | "datetime" | "status"
  align?: "start" | "end" | "center"
}

type SummaryConfig = {
  key: string
  label: Record<Lang, string>
  icon: typeof Landmark
  tone: "default" | "gold" | "success" | "warning" | "danger" | "info" | "processing"
  format?: "money" | "gold" | "number"
}

type ReportFilters = {
  date_from: string
  date_to: string
  as_of_date: string
  customer_id: string
  account_code: string
  account_type: string
  branch_id: string
  karat: string
  vault_id: string
  movement_type: string
  include_cash: string
  include_gold: string
}

type SortState = { key: string; direction: "asc" | "desc" } | null

const lang = (): Lang => (i18n.language?.startsWith("en") ? "en" : "ar")
const t = (ar: string, en: string) => (lang() === "ar" ? ar : en)

const today = () => new Date().toISOString().slice(0, 10)
const thirtyDaysAgo = () => {
  const date = new Date()
  date.setDate(date.getDate() - 30)
  return date.toISOString().slice(0, 10)
}

const emptyFilters: ReportFilters = {
  date_from: thirtyDaysAgo(),
  date_to: today(),
  as_of_date: today(),
  customer_id: "",
  account_code: "",
  account_type: "",
  branch_id: "",
  karat: "",
  vault_id: "",
  movement_type: "",
  include_cash: "true",
  include_gold: "true",
}

const reports: ReportConfig[] = [
  {
    code: "general_ledger",
    category: "accounting",
    title: { ar: "الأستاذ العام", en: "General Ledger" },
    description: { ar: "حركات الحساب مع الرصيد الجاري", en: "Account movements with running balance" },
    endpoint: ENDPOINTS.REPORTS.GENERAL_LEDGER,
    icon: Landmark,
    requires: ["date_from", "date_to"],
    defaultFilters: {},
    summary: [
      { key: "opening_balance", label: { ar: "الرصيد الافتتاحي", en: "Opening Balance" }, icon: Wallet, tone: "info", format: "money" },
      { key: "total_debits", label: { ar: "إجمالي المدين", en: "Total Debits" }, icon: ArrowDownUp, tone: "success", format: "money" },
      { key: "total_credits", label: { ar: "إجمالي الدائن", en: "Total Credits" }, icon: ArrowDownUp, tone: "warning", format: "money" },
      { key: "closing_balance", label: { ar: "الرصيد الختامي", en: "Closing Balance" }, icon: Landmark, tone: "gold", format: "money" },
    ],
    columns: [
      { key: "journal_date", label: { ar: "التاريخ", en: "Date" }, format: "date" },
      { key: "journal_number", label: { ar: "رقم القيد", en: "Journal No." } },
      { key: "description", label: { ar: "الوصف", en: "Description" } },
      { key: "source", label: { ar: "المصدر", en: "Source" } },
      { key: "debit", label: { ar: "مدين", en: "Debit" }, format: "money", align: "end" },
      { key: "credit", label: { ar: "دائن", en: "Credit" }, format: "money", align: "end" },
      { key: "running_balance", label: { ar: "الرصيد الجاري", en: "Running Balance" }, format: "money", align: "end" },
      { key: "reference_type", label: { ar: "المرجع", en: "Reference" } },
    ],
  },
  {
    code: "trial_balance",
    category: "accounting",
    title: { ar: "ميزان المراجعة", en: "Trial Balance" },
    description: { ar: "أرصدة الحسابات وحالة التوازن", en: "Account balances and balance status" },
    endpoint: ENDPOINTS.REPORTS.TRIAL_BALANCE,
    icon: BarChart3,
    requires: ["as_of_date"],
    defaultFilters: {},
    summary: [
      { key: "total_debits", label: { ar: "إجمالي المدين", en: "Total Debits" }, icon: ArrowDownUp, tone: "success", format: "money" },
      { key: "total_credits", label: { ar: "إجمالي الدائن", en: "Total Credits" }, icon: ArrowDownUp, tone: "warning", format: "money" },
      { key: "imbalance", label: { ar: "الفرق", en: "Difference" }, icon: AlertTriangle, tone: "danger", format: "money" },
      { key: "account_count", label: { ar: "عدد الحسابات", en: "Accounts" }, icon: Landmark, tone: "info", format: "number" },
    ],
    columns: [
      { key: "code", label: { ar: "كود الحساب", en: "Account Code" } },
      { key: "name", label: { ar: "اسم الحساب", en: "Account Name" } },
      { key: "account_type", label: { ar: "النوع", en: "Type" } },
      { key: "debit_balance", label: { ar: "ختامي مدين", en: "Debit Balance" }, format: "money", align: "end" },
      { key: "credit_balance", label: { ar: "ختامي دائن", en: "Credit Balance" }, format: "money", align: "end" },
      { key: "net_balance", label: { ar: "الصافي", en: "Net" }, format: "money", align: "end" },
    ],
  },
  {
    code: "customer_statement",
    category: "accounting",
    title: { ar: "كشف العميل", en: "Customer Statement" },
    description: { ar: "حركات المحافظ النقدية والذهبية للعميل", en: "Customer cash and gold wallet movements" },
    endpoint: ENDPOINTS.REPORTS.CUSTOMER_STATEMENT,
    icon: UserRound,
    requires: ["customer_id", "date_from", "date_to"],
    defaultFilters: {},
    summary: [
      { key: "wallet_count", label: { ar: "المحافظ", en: "Wallets" }, icon: Wallet, tone: "info", format: "number" },
      { key: "total_debits", label: { ar: "إجمالي السحب", en: "Total Debits" }, icon: ArrowDownUp, tone: "warning", format: "number" },
      { key: "total_credits", label: { ar: "إجمالي الإضافة", en: "Total Credits" }, icon: ArrowDownUp, tone: "success", format: "number" },
    ],
    columns: [
      { key: "entry_date", label: { ar: "التاريخ", en: "Date" }, format: "date" },
      { key: "wallet_type", label: { ar: "نوع المحفظة", en: "Wallet Type" } },
      { key: "wallet_label", label: { ar: "المحفظة", en: "Wallet" } },
      { key: "entry_type", label: { ar: "نوع الحركة", en: "Movement" } },
      { key: "debit", label: { ar: "مدين", en: "Debit" }, format: "number", align: "end" },
      { key: "credit", label: { ar: "دائن", en: "Credit" }, format: "number", align: "end" },
      { key: "balance_after", label: { ar: "الرصيد بعد الحركة", en: "Balance After" }, format: "number", align: "end" },
      { key: "reference_type", label: { ar: "المرجع", en: "Reference" } },
    ],
  },
  {
    code: "gold_balance",
    category: "gold",
    title: { ar: "أرصدة الذهب", en: "Gold Balances" },
    description: { ar: "تغطية الذهب حسب العيار والخزنة", en: "Gold coverage by karat and vault" },
    endpoint: ENDPOINTS.REPORTS.GOLD_BALANCES,
    icon: Coins,
    requires: [],
    defaultFilters: {},
    summary: [
      { key: "total_physical_weight", label: { ar: "الوزن الفعلي", en: "Physical Weight" }, icon: Coins, tone: "gold", format: "gold" },
      { key: "total_allocated_client_weight", label: { ar: "المخصص للعملاء", en: "Client Allocated" }, icon: UserRound, tone: "info", format: "gold" },
      { key: "total_reserved_weight", label: { ar: "المحجوز", en: "Reserved" }, icon: Wallet, tone: "warning", format: "gold" },
      { key: "total_available_weight", label: { ar: "المتاح", en: "Available" }, icon: Coins, tone: "success", format: "gold" },
    ],
    columns: [
      { key: "karat", label: { ar: "العيار", en: "Karat" }, format: "number" },
      { key: "vault_name", label: { ar: "الخزنة", en: "Vault" } },
      { key: "purity_name", label: { ar: "الملكية/العيار", en: "Ownership/Purity" } },
      { key: "physical_weight", label: { ar: "الوزن", en: "Weight" }, format: "gold", align: "end" },
      { key: "available_weight", label: { ar: "المتاح", en: "Available" }, format: "gold", align: "end" },
      { key: "coverage_ratio", label: { ar: "نسبة التغطية", en: "Coverage" }, format: "number", align: "end" },
      { key: "coverage_status", label: { ar: "الحالة", en: "Status" }, format: "status" },
    ],
  },
  {
    code: "gold_movement",
    category: "gold",
    title: { ar: "حركة الذهب", en: "Gold Movement" },
    description: { ar: "حركات الذهب بين الخزائن والعمليات", en: "Gold movements across vaults and operations" },
    endpoint: ENDPOINTS.REPORTS.GOLD_MOVEMENTS,
    icon: ArrowDownUp,
    requires: [],
    defaultFilters: {},
    summary: [
      { key: "total_in_grams", label: { ar: "الوارد", en: "Inbound" }, icon: ArrowDownUp, tone: "success", format: "gold" },
      { key: "total_out_grams", label: { ar: "الصادر", en: "Outbound" }, icon: ArrowDownUp, tone: "warning", format: "gold" },
      { key: "net_grams", label: { ar: "الصافي", en: "Net" }, icon: Coins, tone: "gold", format: "gold" },
      { key: "movement_count", label: { ar: "عدد الحركات", en: "Movements" }, icon: BarChart3, tone: "info", format: "number" },
    ],
    columns: [
      { key: "movement_date", label: { ar: "التاريخ", en: "Date" }, format: "datetime" },
      { key: "movement_type", label: { ar: "نوع الحركة", en: "Movement Type" } },
      { key: "from_vault_name", label: { ar: "من خزنة", en: "From Vault" } },
      { key: "to_vault_name", label: { ar: "إلى خزنة", en: "To Vault" } },
      { key: "purity_karat", label: { ar: "العيار", en: "Karat" }, format: "number" },
      { key: "grams", label: { ar: "الوزن", en: "Weight" }, format: "gold", align: "end" },
      { key: "source", label: { ar: "المصدر", en: "Source" } },
      { key: "direction", label: { ar: "الحالة", en: "Status" }, format: "status" },
    ],
  },
  {
    code: "vault_balance",
    category: "gold",
    title: { ar: "أرصدة الخزائن", en: "Vault Balances" },
    description: { ar: "عرض أرصدة الخزائن من تقرير أرصدة الذهب", en: "Vault balances derived from gold balance data" },
    endpoint: ENDPOINTS.REPORTS.GOLD_BALANCES,
    icon: Wallet,
    requires: [],
    defaultFilters: {},
    summary: [
      { key: "total_physical_weight", label: { ar: "إجمالي الخزائن", en: "Vault Total" }, icon: Wallet, tone: "gold", format: "gold" },
      { key: "total_reserved_weight", label: { ar: "محجوز", en: "Reserved" }, icon: Coins, tone: "warning", format: "gold" },
      { key: "total_available_weight", label: { ar: "متاح", en: "Available" }, icon: Coins, tone: "success", format: "gold" },
    ],
    columns: [
      { key: "vault_name", label: { ar: "الخزنة", en: "Vault" } },
      { key: "karat", label: { ar: "العيار", en: "Karat" }, format: "number" },
      { key: "physical_weight", label: { ar: "الوزن", en: "Weight" }, format: "gold", align: "end" },
      { key: "reserved_weight", label: { ar: "المحجوز", en: "Reserved" }, format: "gold", align: "end" },
      { key: "available_weight", label: { ar: "المتاح", en: "Available" }, format: "gold", align: "end" },
      { key: "coverage_status", label: { ar: "الحالة", en: "Status" }, format: "status" },
    ],
  },
  {
    code: "fees_profit",
    category: "revenue",
    title: { ar: "الرسوم والأرباح", en: "Fees and Profit" },
    description: { ar: "ملخص الإيرادات والمصروفات وصافي الربح", en: "Revenue, expenses, fees, and net profit" },
    endpoint: ENDPOINTS.REPORTS.FEES_PROFIT,
    icon: FileText,
    requires: ["date_from", "date_to"],
    defaultFilters: {},
    summary: [
      { key: "total_fees", label: { ar: "الرسوم", en: "Fees" }, icon: FileText, tone: "info", format: "money" },
      { key: "total_revenue", label: { ar: "الإيرادات", en: "Revenue" }, icon: BarChart3, tone: "success", format: "money" },
      { key: "total_expenses", label: { ar: "المصروفات", en: "Expenses" }, icon: ArrowDownUp, tone: "warning", format: "money" },
      { key: "net_profit", label: { ar: "صافي الربح", en: "Net Profit" }, icon: Landmark, tone: "gold", format: "money" },
    ],
    columns: [
      { key: "section", label: { ar: "القسم", en: "Section" } },
      { key: "code", label: { ar: "كود الحساب", en: "Account Code" } },
      { key: "name", label: { ar: "اسم الحساب", en: "Account Name" } },
      { key: "total_debits", label: { ar: "مدين", en: "Debits" }, format: "money", align: "end" },
      { key: "total_credits", label: { ar: "دائن", en: "Credits" }, format: "money", align: "end" },
      { key: "net_amount", label: { ar: "الصافي", en: "Net" }, format: "money", align: "end" },
    ],
  },
]

function label(value: Record<Lang, string>) {
  return value[lang()]
}

function normalizeRow(report: ReportConfig, row: Record<string, unknown>) {
  const next = { ...row }
  if (report.code === "general_ledger") {
    next.debit = row.entry_type === "debit" ? row.amount : null
    next.credit = row.entry_type === "credit" ? row.amount : null
  }
  next.name = row.name_en || row.name_ar || row.account_name_en || row.account_name_ar
  next.purity_name = row.purity_name_en || row.purity_name_ar
  return next
}

function collectValue(payload: ReportPayload | null, key: string) {
  if (!payload) return null
  return payload.summary?.[key] ?? payload.totals?.[key] ?? payload.raw?.[key] ?? null
}

function formatCell(value: unknown, format?: ColumnConfig["format"]) {
  if (value === null || value === undefined || value === "") return "-"
  if (format === "money") return formatMoney(String(value), "USD")
  if (format === "gold") return formatGold(String(value))
  if (format === "number") return formatNumber(String(value), 2)
  if (format === "date") return String(value).slice(0, 10)
  if (format === "datetime") return formatDateTime(String(value))
  return String(value)
}

function formatSummary(value: unknown, format?: SummaryConfig["format"]) {
  if (value === null || value === undefined || value === "") return "-"
  if (format === "money") return formatMoney(String(value), "USD")
  if (format === "gold") return formatGold(String(value))
  if (format === "number") return formatNumber(String(value), 0)
  return String(value)
}

function alignClass(align?: ColumnConfig["align"]) {
  if (align === "center") return "text-center"
  if (align === "end") return "text-left"
  return "text-right"
}

export default function ReportsPage() {
  const searchParams = useSearchParams()
  const initialReport = reports.some((report) => report.code === searchParams.get("report"))
    ? searchParams.get("report") as ReportCode
    : "general_ledger"
  const [selectedCode, setSelectedCode] = useState<ReportCode>(initialReport)
  const [filters, setFilters] = useState<ReportFilters>(emptyFilters)
  const [sort, setSort] = useState<SortState>(null)
  const [quickFilter, setQuickFilter] = useState("")
  const [pdfExporting, setPdfExporting] = useState(false)
  const {
    report: payload,
    isLoading,
    exporting,
    error,
    setError,
    generateReport,
    exportReport: downloadReport,
    clearReport,
  } = useReports()
  const customers = useCustomers()
  const branches = useBranches()
  const vaults = useVaults()

  useEffect(() => {
    customers.fetchItems(1, 100, "", { status: "active" })
    branches.fetchItems(1, 100)
    vaults.fetchItems(1, 100)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const selectedReport = reports.find((report) => report.code === selectedCode) ?? reports[0]
  const Icon = selectedReport.icon

  const rows = useMemo(() => {
    const normalized = (payload?.rows ?? []).map((row) => normalizeRow(selectedReport, row))
    const filtered = quickFilter
      ? normalized.filter((row) => JSON.stringify(row).toLowerCase().includes(quickFilter.toLowerCase()))
      : normalized
    if (!sort) return filtered
    return [...filtered].sort((a, b) => {
      const av = String(a[sort.key] ?? "")
      const bv = String(b[sort.key] ?? "")
      return sort.direction === "asc" ? av.localeCompare(bv) : bv.localeCompare(av)
    })
  }, [payload, quickFilter, selectedReport, sort])

  const customerOptions: SearchableSelectOption[] = useMemo(() => {
    return customers.items
      .filter((customer) => customer.status === "active")
      .map((customer) => ({
        value: customer.id,
        label: customer.name || customer.customer_code || customer.email || customer.phone || customer.id,
        description: [customer.customer_code, customer.email, customer.phone].filter(Boolean).join(" - "),
      }))
  }, [customers.items])

  const branchOptions: SearchableSelectOption[] = useMemo(() => {
    return branches.items.map((branch) => ({
      value: branch.id,
      label: branch.name_ar || branch.name_en || branch.code || branch.id,
      description: branch.code,
    }))
  }, [branches.items])

  const vaultOptions: SearchableSelectOption[] = useMemo(() => {
    return vaults.items.map((vault) => ({
      value: vault.id,
      label: vault.name || vault.code || vault.id,
      description: [vault.code, vault.status].filter(Boolean).join(" - "),
    }))
  }, [vaults.items])

  const updateFilter = (key: keyof ReportFilters, value: string) => {
    setFilters((current) => ({ ...current, [key]: value }))
  }

  const resolveEndpoint = () => {
    if (typeof selectedReport.endpoint === "function") {
      return selectedReport.endpoint(filters.customer_id.trim())
    }
    return selectedReport.endpoint
  }

  const buildParams = (format?: ReportExportFormat) => {
    const params: Record<string, string> = {}
    if (selectedReport.code === "trial_balance") {
      params.as_of_date = filters.as_of_date
      if (filters.date_from) params.from_date = filters.date_from
    } else if (selectedReport.code === "gold_movement") {
      if (filters.date_from) params.from_date = `${filters.date_from}T00:00:00`
      if (filters.date_to) params.to_date = `${filters.date_to}T23:59:59`
    } else if (selectedReport.code !== "gold_balance" && selectedReport.code !== "vault_balance") {
      if (filters.date_from) params.date_from = filters.date_from
      if (filters.date_to) params.date_to = filters.date_to
      if (selectedReport.code === "customer_statement") {
        params.from_date = filters.date_from
        delete params.date_from
      }
      if (selectedReport.code === "fees_profit") {
        params.from_date = filters.date_from
        delete params.date_from
      }
    }

    if (filters.account_code && selectedReport.code === "general_ledger") params.account_code = filters.account_code
    if (filters.account_type && selectedReport.code === "general_ledger") params.account_type = filters.account_type
    if (filters.branch_id && ["general_ledger", "trial_balance", "fees_profit"].includes(selectedReport.code)) params.branch_id = filters.branch_id
    if (filters.karat && ["gold_balance", "vault_balance"].includes(selectedReport.code)) params.karat = filters.karat
    if (filters.vault_id && ["gold_balance", "vault_balance", "gold_movement"].includes(selectedReport.code)) params.vault_id = filters.vault_id
    if (filters.movement_type && selectedReport.code === "gold_movement") params.movement_type = filters.movement_type
    if (selectedReport.code === "customer_statement") {
      params.include_cash = filters.include_cash
      params.include_gold = filters.include_gold
    }
    if (format) params.format = format
    return params
  }

  const optionLabel = (options: SearchableSelectOption[], value: string) => {
    return options.find((option) => option.value === value)?.label || value
  }

  const buildPdfFilters = () => {
    const output: ReportPdfFilter[] = []
    const add = (condition: boolean, labelText: string, value: string) => {
      if (condition) output.push({ label: labelText, value: value || "-" })
    }

    add(!!filters.date_from && selectedReport.code !== "gold_balance" && selectedReport.code !== "vault_balance", t("من تاريخ", "From Date"), filters.date_from)
    add(!!filters.date_to && selectedReport.code !== "trial_balance" && selectedReport.code !== "gold_balance" && selectedReport.code !== "vault_balance", t("إلى تاريخ", "To Date"), filters.date_to)
    add(selectedReport.code === "trial_balance", t("حتى تاريخ", "As Of Date"), filters.as_of_date)
    add(!!filters.customer_id && selectedReport.code === "customer_statement", t("العميل", "Customer"), optionLabel(customerOptions, filters.customer_id))
    add(!!filters.account_code && selectedReport.code === "general_ledger", t("الحساب", "Account"), filters.account_code)
    add(!!filters.account_type && selectedReport.code === "general_ledger", t("نوع الحساب", "Account Type"), filters.account_type)
    add(!!filters.branch_id && ["general_ledger", "trial_balance", "fees_profit"].includes(selectedReport.code), t("الفرع", "Branch"), optionLabel(branchOptions, filters.branch_id))
    add(!!filters.karat && ["gold_balance", "vault_balance"].includes(selectedReport.code), t("العيار", "Karat"), filters.karat)
    add(!!filters.vault_id && ["gold_balance", "vault_balance", "gold_movement"].includes(selectedReport.code), t("الخزنة", "Vault"), optionLabel(vaultOptions, filters.vault_id))
    add(!!filters.movement_type && selectedReport.code === "gold_movement", t("نوع الحركة", "Movement Type"), filters.movement_type)
    add(selectedReport.code === "customer_statement", t("الحركات المالية", "Cash Movements"), filters.include_cash === "true" ? t("عرض", "Show") : t("إخفاء", "Hide"))
    add(selectedReport.code === "customer_statement", t("الحركات الذهبية", "Gold Movements"), filters.include_gold === "true" ? t("عرض", "Show") : t("إخفاء", "Hide"))

    return output
  }

  const buildPdfMetrics = (reportPayload: ReportPayload) => {
    return selectedReport.summary.map<ReportPdfMetric>((item) => ({
      label: label(item.label),
      value: formatSummary(collectValue(reportPayload, item.key), item.format),
    }))
  }

  const buildPdfRows = (reportPayload: ReportPayload) => {
    return reportPayload.rows.map<ReportPdfRow>((row) => {
      const normalized = normalizeRow(selectedReport, row)
      return selectedReport.columns.reduce<ReportPdfRow>((acc, column) => {
        acc[column.key] = formatCell(normalized[column.key], column.format)
        return acc
      }, {})
    })
  }

  const printPdfReport = (reportPayload: ReportPayload) => {
    const language = i18n.language || "ar"
    printReportPdf(
      {
        title: label(selectedReport.title),
        subtitle: label(selectedReport.description),
        reportCode: selectedReport.code,
        language,
        generatedAt: reportPayload.generated_at,
        generatedBy: reportPayload.generated_by,
        filters: buildPdfFilters(),
        metrics: buildPdfMetrics(reportPayload),
        columns: selectedReport.columns.map((column) => ({
          key: column.key,
          label: label(column.label),
          align: column.align,
        })),
        rows: buildPdfRows(reportPayload),
        labels: {
          generated: t("تاريخ الإنشاء", "Generated"),
          generatedBy: t("منشئ التقرير", "Generated By"),
          filters: t("الفلاتر", "Filters"),
          summary: t("الملخص", "Summary"),
          results: t("النتائج", "Results"),
          noData: t("لا توجد بيانات حسب الفلاتر المحددة", "No data for the selected filters"),
          dashboard: t("لوحة إدارة محفظة الذهب", "Gold Wallet Admin Dashboard"),
          confidential: t("مستند تقرير سري", "Confidential report document"),
          rows: t("عدد الصفوف", "Rows"),
        },
      },
      `${selectedReport.code}-${today()}.pdf`,
    )
  }

  const validateRequired = () => {
    const missing = selectedReport.requires.filter((key) => !filters[key as keyof ReportFilters])
    if (missing.length) {
      setError(t("يرجى إدخال الفلاتر الإلزامية", "Please enter the required filters"))
      return false
    }
    return true
  }

  const runReport = async () => {
    setError(null)
    clearReport()
    if (!validateRequired()) return
    try {
      await generateReport({ endpoint: resolveEndpoint(), params: buildParams() })
      setSort(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : t("تعذر توليد التقرير", "Unable to generate report"))
    }
  }

  const exportReport = async (format: ReportExportFormat) => {
    setError(null)
    if (!validateRequired()) return
    try {
      if (format === "pdf") {
        setPdfExporting(true)
        const reportPayload = await generateReport({ endpoint: resolveEndpoint(), params: buildParams() })
        printPdfReport(reportPayload)
        setSort(null)
        return
      }
      await downloadReport({
        endpoint: resolveEndpoint(),
        params: buildParams(),
        reportCode: selectedReport.code,
        format,
      })
    } catch (err) {
      setError(err instanceof Error ? err.message : t("تعذر تصدير التقرير", "Unable to export report"))
    } finally {
      setPdfExporting(false)
    }
  }

  const toggleSort = (key: string) => {
    setSort((current) => {
      if (!current || current.key !== key) return { key, direction: "asc" }
      return { key, direction: current.direction === "asc" ? "desc" : "asc" }
    })
  }

  return (
    <div className="space-y-5">
      <PageHeader
        title={t("التقارير", "Reports")}
        description={t("تقارير المحاسبة والذهب والإيرادات", "Accounting, gold, and revenue reports")}
        breadcrumbs={[{ label: t("لوحة الإدارة", "Admin"), href: "#" }, { label: t("التقارير", "Reports") }]}
      />

      <div className="grid grid-cols-1 gap-4 xl:grid-cols-[300px_1fr]">
        <SectionCard title={t("قائمة التقارير", "Report Menu")} padded={false}>
          <div className="divide-y divide-border">
            {(["accounting", "gold", "revenue"] as const).map((category) => (
              <div key={category} className="p-3">
                <div className="mb-2 px-2 text-[11px] font-bold uppercase tracking-wider text-muted-foreground">
                  {category === "accounting" ? t("التقارير المحاسبية", "Accounting Reports") : category === "gold" ? t("تقارير الذهب", "Gold Reports") : t("تقارير الإيرادات", "Revenue Reports")}
                </div>
                <div className="space-y-1">
                  {reports.filter((report) => report.category === category).map((report) => {
                    const ReportIcon = report.icon
                    const active = report.code === selectedReport.code
                    return (
                      <button
                        key={report.code}
                        type="button"
                        onClick={() => {
                          setSelectedCode(report.code)
                          clearReport()
                          setSort(null)
                        }}
                        className={`flex w-full items-center gap-2 rounded-lg px-3 py-2 text-right text-[13px] font-semibold transition ${active ? "bg-gold-50 text-gold-800 ring-1 ring-gold-200" : "text-foreground hover:bg-muted"}`}
                      >
                        <ReportIcon className="h-4 w-4 shrink-0" />
                        <span className="flex-1">{label(report.title)}</span>
                      </button>
                    )
                  })}
                </div>
              </div>
            ))}
          </div>
        </SectionCard>

        <div className="space-y-4">
          <SectionCard
            className="overflow-visible"
            title={
              <span className="inline-flex items-center gap-2">
                <Icon className="h-4 w-4 text-gold-600" />
                {label(selectedReport.title)}
              </span>
            }
            description={label(selectedReport.description)}
            actions={
              <div className="flex flex-wrap gap-2">
                <button
                  type="button"
                  onClick={() => exportReport("pdf")}
                  disabled={!!exporting || pdfExporting || isLoading}
                  className="inline-flex h-9 items-center gap-2 rounded-md border border-border bg-card px-3 text-[12px] font-semibold hover:bg-muted disabled:opacity-50"
                >
                  <Download className="h-4 w-4" /> {pdfExporting ? t("جار التصدير", "Exporting") : "PDF"}
                </button>
                <button
                  type="button"
                  onClick={() => exportReport("xlsx")}
                  disabled={!!exporting || pdfExporting || isLoading}
                  className="inline-flex h-9 items-center gap-2 rounded-md border border-border bg-card px-3 text-[12px] font-semibold hover:bg-muted disabled:opacity-50"
                >
                  <FileSpreadsheet className="h-4 w-4" /> {exporting === "xlsx" ? t("جار التصدير", "Exporting") : "Excel"}
                </button>
              </div>
            }
          >
            <form
              onSubmit={(event) => {
                event.preventDefault()
                runReport()
              }}
              className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4"
            >
              {selectedReport.code === "customer_statement" && (
                <SearchableSelectField
                  label={t("العميل", "Customer")}
                  id="customer_id"
                  value={filters.customer_id}
                  onChange={(value) => updateFilter("customer_id", value)}
                  options={customerOptions}
                  placeholder={t("ابحث بالاسم أو الكود أو الهاتف", "Search by name, code, or phone")}
                  required
                  disabled={customers.isLoading}
                />
              )}
              {selectedReport.code !== "trial_balance" && selectedReport.code !== "gold_balance" && selectedReport.code !== "vault_balance" && (
                <>
                  <InputField label={t("من تاريخ", "From Date")} id="date_from" name="date_from" type="date" value={filters.date_from} onChange={(event) => updateFilter("date_from", event.target.value)} required={selectedReport.requires.includes("date_from")} />
                  <InputField label={t("إلى تاريخ", "To Date")} id="date_to" name="date_to" type="date" value={filters.date_to} onChange={(event) => updateFilter("date_to", event.target.value)} required={selectedReport.requires.includes("date_to")} />
                </>
              )}
              {selectedReport.code === "trial_balance" && (
                <>
                  <InputField label={t("من تاريخ", "From Date")} id="date_from" name="date_from" type="date" value={filters.date_from} onChange={(event) => updateFilter("date_from", event.target.value)} />
                  <InputField label={t("حتى تاريخ", "As Of Date")} id="as_of_date" name="as_of_date" type="date" value={filters.as_of_date} onChange={(event) => updateFilter("as_of_date", event.target.value)} required />
                </>
              )}
              {selectedReport.code === "general_ledger" && (
                <>
                  <InputField label={t("الحساب", "Account")} id="account_code" name="account_code" value={filters.account_code} onChange={(event) => updateFilter("account_code", event.target.value)} placeholder="1001" />
                  <SelectField label={t("نوع الحساب", "Account Type")} id="account_type" name="account_type" value={filters.account_type} onChange={(event) => updateFilter("account_type", event.target.value)} options={[
                    { value: "asset", label: t("أصول", "Asset") },
                    { value: "liability", label: t("التزامات", "Liability") },
                    { value: "equity", label: t("حقوق ملكية", "Equity") },
                    { value: "revenue", label: t("إيرادات", "Revenue") },
                    { value: "expense", label: t("مصروفات", "Expense") },
                  ]} />
                </>
              )}
              {["general_ledger", "trial_balance", "fees_profit"].includes(selectedReport.code) && (
                <SearchableSelectField
                  label={t("الفرع", "Branch")}
                  id="branch_id"
                  value={filters.branch_id}
                  onChange={(value) => updateFilter("branch_id", value)}
                  options={branchOptions}
                  placeholder={t("ابحث باسم الفرع أو الكود", "Search branch name or code")}
                  disabled={branches.isLoading}
                />
              )}
              {["gold_balance", "gold_movement", "vault_balance"].includes(selectedReport.code) && (
                <>
                  <InputField label={t("العيار", "Karat")} id="karat" name="karat" type="number" min={1} max={24} value={filters.karat} onChange={(event) => updateFilter("karat", event.target.value)} />
                  <SearchableSelectField
                    label={t("الخزنة", "Vault")}
                    id="vault_id"
                    value={filters.vault_id}
                    onChange={(value) => updateFilter("vault_id", value)}
                    options={vaultOptions}
                    placeholder={t("ابحث باسم الخزنة أو الكود", "Search vault name or code")}
                    disabled={vaults.isLoading}
                  />
                </>
              )}
              {selectedReport.code === "gold_movement" && (
                <InputField label={t("نوع الحركة", "Movement Type")} id="movement_type" name="movement_type" value={filters.movement_type} onChange={(event) => updateFilter("movement_type", event.target.value)} />
              )}
              {selectedReport.code === "customer_statement" && (
                <>
                  <SelectField label={t("الحركات المالية", "Cash Movements")} id="include_cash" name="include_cash" value={filters.include_cash} onChange={(event) => updateFilter("include_cash", event.target.value)} options={[{ value: "true", label: t("عرض", "Show") }, { value: "false", label: t("إخفاء", "Hide") }]} />
                  <SelectField label={t("الحركات الذهبية", "Gold Movements")} id="include_gold" name="include_gold" value={filters.include_gold} onChange={(event) => updateFilter("include_gold", event.target.value)} options={[{ value: "true", label: t("عرض", "Show") }, { value: "false", label: t("إخفاء", "Hide") }]} />
                </>
              )}
              <div className="flex items-end">
                <button type="submit" disabled={isLoading} className="inline-flex h-[42px] w-full items-center justify-center gap-2 rounded-lg bg-gold-600 px-4 text-sm font-bold text-white hover:bg-gold-700 disabled:opacity-50">
                  <Search className="h-4 w-4" /> {isLoading ? t("جار البحث", "Searching") : t("بحث", "Search")}
                </button>
              </div>
            </form>
          </SectionCard>

          {error && (
            <div className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">
              <AlertTriangle className="h-4 w-4" />
              {error}
            </div>
          )}

          {payload && (
            <>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
                {selectedReport.summary.map((item) => (
                  <KpiCard
                    key={item.key}
                    label={label(item.label)}
                    value={formatSummary(collectValue(payload, item.key), item.format)}
                    icon={item.icon}
                    tone={item.tone}
                    accent={item.tone === "gold"}
                  />
                ))}
              </div>

              {selectedReport.code === "trial_balance" && Number(collectValue(payload, "imbalance") ?? 0) !== 0 && (
                <div className="flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800">
                  <AlertTriangle className="h-4 w-4" />
                  {t("ميزان المراجعة غير متوازن، يرجى مراجعة القيود.", "Trial balance is not balanced. Please review journal entries.")}
                </div>
              )}

              <SectionCard
                title={t("النتائج", "Results")}
                description={`${t("تم التوليد", "Generated")} ${formatDateTime(payload.generated_at)}${payload.generated_by ? ` - ${payload.generated_by}` : ""}`}
                actions={
                  <div className="w-56">
                    <InputField label={t("تصفية الجدول", "Filter Table")} id="quick_filter" name="quick_filter" value={quickFilter} onChange={(event) => setQuickFilter(event.target.value)} />
                  </div>
                }
                padded={false}
              >
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse text-right">
                    <thead>
                      <tr className="border-b border-border bg-muted/50">
                        {selectedReport.columns.map((column) => (
                          <th key={column.key} className={`whitespace-nowrap px-4 py-3 text-[11px] font-bold uppercase tracking-wider text-muted-foreground ${alignClass(column.align)}`}>
                            <button type="button" onClick={() => toggleSort(column.key)} className="inline-flex items-center gap-1 hover:text-foreground">
                              {label(column.label)}
                              <ArrowDownUp className="h-3 w-3" />
                            </button>
                          </th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {isLoading && (
                        <tr>
                          <td colSpan={selectedReport.columns.length} className="px-5 py-10 text-center text-sm text-muted-foreground">{t("جار تحميل البيانات", "Loading data")}</td>
                        </tr>
                      )}
                      {!isLoading && rows.length === 0 && (
                        <tr>
                          <td colSpan={selectedReport.columns.length} className="px-5 py-10 text-center text-sm text-muted-foreground">{t("لا توجد بيانات حسب الفلاتر المحددة", "No data for the selected filters")}</td>
                        </tr>
                      )}
                      {!isLoading && rows.map((row, index) => (
                        <tr key={String(row.id || row.entry_id || row.movement_id || index)} className="border-b border-border/70 hover:bg-muted/30">
                          {selectedReport.columns.map((column) => (
                            <td key={column.key} className={`max-w-[260px] truncate px-4 py-3 text-[13px] tabular-nums ${alignClass(column.align)}`}>
                              {formatCell(row[column.key], column.format)}
                            </td>
                          ))}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </SectionCard>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
