'use client'

import { useState, useEffect } from "react"
import { PageHeader } from "@/components/ui/page-header"
import { KpiCard } from "@/components/ui/kpi-card"
import { SectionCard } from "@/components/ui/section-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { AvatarBadge } from "@/components/ui/avatar-badge"
import { Wallet, Download, Upload, ShieldCheck, DollarSign } from "lucide-react"
import { fmtMoney, formatDateTime } from "@/lib/format"
import { useCashWallets, useWalletLedger } from "@/hooks/useWallets"
import { useWalletEngine } from "@/hooks/useWalletEngine"
import type { CashWalletDTO } from "@/types"

import { Modal, ModalActions } from "@/components/ui/modal"
import { Button } from "@/components/ui/button"

import { FilterToolbar } from "@/components/ui/filter-toolbar"
import { InputField } from "@/components/ui/FormFields"
import i18n from "@/lib/i18n";

export default function CashWalletPage() {
  const { items: wallets, isLoading, fetchItems: refreshWallets } = useCashWallets()
  const { getCashLedger } = useWalletLedger()
  const { moveCash } = useWalletEngine()

  // (Removed empty useEffect here to avoid double fetching since we have the debounce one now)

  const [selected, setSelected] = useState<CashWalletDTO | null>(null)
  const [movements, setMovements] = useState<any[]>([])
  
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [opType, setOpType] = useState<"deposit" | "withdraw">("deposit")
  const [amount, setAmount] = useState("")
  const [description, setDescription] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  
  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selected) return
    setIsSubmitting(true)
    try {
      const coa_account_id = "00000000-0000-0000-0000-000000000000"
      await moveCash({
        user_id: selected.user_id,
        wallet_id: selected.id,
        amount: Number(amount),
        coa_account_id,
        description: description || `Manual ${opType}`,
        type: opType,
      })
      setIsModalOpen(false)
      refreshWallets(1, 50, searchQuery)
      const newMovements = await getCashLedger(selected.id)
      setMovements(newMovements)
    } finally {
      setIsSubmitting(false)
    }
  }

  const openModal = (type: "deposit" | "withdraw") => {
    setOpType(type)
    setAmount("")
    setDescription("")
    setIsModalOpen(true)
  }

  const [searchQuery, setSearchQuery] = useState("")

  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      refreshWallets(1, 50, searchQuery)
    }, 500)
    return () => clearTimeout(delayDebounceFn)
  }, [refreshWallets, searchQuery])

  useEffect(() => {
    if (selected) {
      const updated = wallets.find((w) => w.id === selected.id)
      if (updated) {
        setSelected(updated)
      } else if (wallets.length > 0) {
        setSelected(wallets[0])
      }
    } else if (wallets.length > 0) {
      setSelected(wallets[0])
    }
  }, [wallets])

  useEffect(() => {
    if (selected) {
      getCashLedger(selected.id).then(setMovements).catch(console.error)
    } else {
      setMovements([])
    }
  }, [selected])

  const total = wallets.reduce((acc, w) => acc + Number(w.available_balance) + Number(w.reserved_balance), 0)
  const available = wallets.reduce((acc, w) => acc + Number(w.available_balance), 0)
  const held = wallets.reduce((acc, w) => acc + Number(w.reserved_balance), 0)

  const columns: Column<CashWalletDTO>[] = [
    {
      key: "customer",
      header: i18n.t('app.admin.cash-wallet.page.text_1'),
      cell: (r) => (
        <div className="flex items-center gap-2.5">
          <AvatarBadge name={(r as any).customer_name || "—"} size="sm" />
          <span className="text-[13px] font-medium">{(r as any).customer_name || "—"}</span>
        </div>
      ),
    },
    { key: "wallet", header: i18n.t('app.admin.cash-wallet.page.text_2'), cell: (r) => <span className="font-mono text-[12.5px]">{r.id.split("-")[0]}</span> },
    { key: "available", header: i18n.t('app.admin.cash-wallet.page.text_3'), cell: (r) => <span className="font-mono tabular-nums text-[13px] font-semibold">{fmtMoney(r.available_balance, r.currency_code)}</span> },
    {
      key: "held",
      header: i18n.t('app.admin.cash-wallet.page.text_4'),
      cell: (r) => <span className={`font-mono tabular-nums text-[13px] ${Number(r.reserved_balance) > 0 ? "text-amber-600 font-semibold" : "text-muted-foreground"}`}>{fmtMoney(r.reserved_balance, r.currency_code)}</span>,
    },
    {
      key: "total",
      header: i18n.t('app.admin.cash-wallet.page.text_5'),
      cell: (r) => <span className="font-mono tabular-nums text-[13px] font-semibold">{fmtMoney(Number(r.available_balance) + Number(r.reserved_balance), r.currency_code)}</span>,
    },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title={i18n.t('app.admin.cash-wallet.page.text_6')}
        description={i18n.t('app.admin.cash-wallet.page.text_7')}
        breadcrumbs={[{ label: i18n.t('app.admin.cash-wallet.page.text_8'), href: "#" }, { label: i18n.t('app.admin.cash-wallet.page.text_9') }]}
      />

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.cash-wallet.page.text_10')} value={fmtMoney(total)} icon={DollarSign} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.cash-wallet.page.text_11')} value={fmtMoney(available)} icon={Wallet} tone="success" />
        <KpiCard label={i18n.t('app.admin.cash-wallet.page.text_12')} value={fmtMoney(held)} icon={ShieldCheck} tone="warning" />
        <KpiCard label={i18n.t('app.admin.cash-wallet.page.text_13')} value={String(wallets.length)} icon={Upload} tone="info" />
      </div>

      <div className="space-y-2">
        <FilterToolbar
          searchValue={searchQuery}
          onSearchChange={setSearchQuery}
          searchPlaceholder={i18n.t('app.admin.cash-wallet.page.text_14')}
          showDate={false}
          showExport={false}
        />

        <div className="grid gap-6 lg:grid-cols-[1fr_400px]">
        <SectionCard title={i18n.t('app.admin.cash-wallet.page.text_15')} padded={false}>
          {isLoading ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.cash-wallet.page.text_27')}</div>
          ) : wallets.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.cash-wallet.page.text_28')}</div>
          ) : (
            <DataTable columns={columns} data={wallets} rowKey={(r) => r.id} activeRowKey={selected?.id} onRowClick={setSelected} />
          )}
        </SectionCard>

        <SectionCard title={selected ? i18n.t('app.admin.wallets.page.text_details', { customer_name: (selected as any).customer_name }) : i18n.t('app.admin.cash-wallet.page.text_16')}>
          {selected ? (
            <div className="space-y-4">
              <div className="rounded-lg border border-gold-200 bg-gradient-to-br from-gold-50/60 to-card p-4 space-y-3">
                <div className="flex items-baseline justify-between">
                  <span className="text-[11.5px] uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.cash-wallet.page.text_29')}</span>
                  <span className="font-mono text-[20px] font-bold tabular-nums">{fmtMoney(selected.available_balance, selected.currency_code)}</span>
                </div>
                <div className="flex items-baseline justify-between border-t border-border/60 pt-2.5">
                  <span className="text-[11.5px] uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.cash-wallet.page.text_30')}</span>
                  <span className="font-mono text-[15px] font-semibold text-amber-700 tabular-nums">{fmtMoney(selected.reserved_balance, selected.currency_code)}</span>
                </div>
              </div>
              <div>
                <p className="text-[12px] font-semibold uppercase tracking-wide text-muted-foreground mb-2.5">{i18n.t('app.admin.cash-wallet.page.text_31')}</p>
                {movements.length === 0 ? (
                  <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.cash-wallet.page.text_32')}</p>
                ) : (
                  <div className="space-y-2 max-h-[300px] overflow-y-auto pr-1">
                    {movements.map((m) => (
                      <div key={m.id} className="flex items-center justify-between rounded-lg border border-border/70 bg-card p-2.5">
                        <div className="flex items-center gap-2.5 min-w-0">
                          <div className={`flex shrink-0 h-7 w-7 items-center justify-center rounded-md ${m.direction === "credit" ? "bg-emerald-50 text-emerald-600" : "bg-red-50 text-red-600"}`}>
                            {m.direction === "credit" ? <Download className="h-3.5 w-3.5" /> : <Upload className="h-3.5 w-3.5" />}
                          </div>
                          <div className="min-w-0">
                            <p className="text-[12.5px] font-medium truncate">{m.description || m.reference_type || i18n.t('app.admin.cash-wallet.page.text_17')}</p>
                            <p className="text-[11px] text-muted-foreground">{formatDateTime(m.created_at)}</p>
                          </div>
                        </div>
                        <div className="flex flex-col items-end shrink-0">
                          <span className={`font-mono text-[12.5px] font-semibold tabular-nums ${m.direction === "credit" ? "text-emerald-600" : "text-red-600"}`}>
                            {m.direction === "credit" ? "+" : "−"}
                            {fmtMoney(m.amount, selected.currency_code)}
                          </span>
                          <span className="text-[10px] text-muted-foreground font-mono">{i18n.t('app.admin.cash-wallet.page.text_33')}{fmtMoney(m.balance_after, selected.currency_code)}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ) : (
            <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.cash-wallet.page.text_36')}</p>
          )}
        </SectionCard>
      </div>
      </div>

      <Modal
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={opType === "deposit" ? i18n.t('app.admin.cash-wallet.page.text_18') : i18n.t('app.admin.cash-wallet.page.text_19')}
        description={i18n.t('app.admin.wallets.page.text_operation', { opType: opType === "deposit" ? i18n.t('app.admin.cash-wallet.page.text_20') : i18n.t('app.admin.cash-wallet.page.text_21'), customer_name: (selected as any)?.customer_name })}
        size="sm"
      >
        <form onSubmit={onSubmit} className="space-y-4">
          <InputField
            id="amount"
            name="amount"
            label={i18n.t('app.admin.cash-wallet.page.text_22')}
            type="number"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            placeholder="0.00"
            required
          />
          <InputField
            id="description"
            name="description"
            label={i18n.t('app.admin.cash-wallet.page.text_23')}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder={i18n.t('app.admin.cash-wallet.page.text_24')}
          />
          <div className="pt-4 border-t border-border">
            <ModalActions>
              <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>{i18n.t('app.admin.cash-wallet.page.text_37')}</Button>
              <Button type="submit" isLoading={isSubmitting}>{opType === "deposit" ? i18n.t('app.admin.cash-wallet.page.text_25') : i18n.t('app.admin.cash-wallet.page.text_26')}</Button>
            </ModalActions>
          </div>
        </form>
      </Modal>
    </div>
  )
}
