'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 { Coins, ShieldCheck, Scale, Sparkles, Download, Upload } from "lucide-react"
import { fmtGrams, fmtOunces, fmtMoney, formatDateTime } from "@/lib/format"
import { useGoldWallets, useWalletLedger } from "@/hooks/useWallets"
import { useWalletEngine } from "@/hooks/useWalletEngine"
import type { GoldWalletDTO } from "@/types"
import { Modal, ModalActions } from "@/components/ui/modal"
import { Button } from "@/components/ui/button"

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

const GRAM_PRICE_USD = 65
const OZ_PER_GRAM = 0.0321507

export default function GoldWalletPage() {
  const { items: wallets, isLoading, fetchItems: refreshWallets } = useGoldWallets()
  const { getGoldLedger } = useWalletLedger()
  const { moveGold } = useWalletEngine()

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

  const [selected, setSelected] = useState<GoldWalletDTO | null>(null)
  const [movements, setMovements] = useState<any[]>([])

  const [isModalOpen, setIsModalOpen] = useState(false)
  const [opType, setOpType] = useState<"deposit" | "withdraw">("deposit")
  const [grams, setGrams] = 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 moveGold({
        user_id: selected.user_id,
        wallet_id: selected.id,
        grams: Number(grams),
        coa_account_id,
        description: description || `Manual ${opType}`,
        type: opType,
      })
      setIsModalOpen(false)
      refreshWallets(1, 50, searchQuery)
      const newMovements = await getGoldLedger(selected.id)
      setMovements(newMovements)
    } finally {
      setIsSubmitting(false)
    }
  }

  const openModal = (type: "deposit" | "withdraw") => {
    setOpType(type)
    setGrams("")
    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) {
      getGoldLedger(selected.id).then(setMovements).catch(console.error)
    } else {
      setMovements([])
    }
  }, [selected])

  const totalG = wallets.reduce((acc, w) => acc + Number(w.available_grams) + Number(w.reserved_grams), 0)
  const heldG = wallets.reduce((acc, w) => acc + Number(w.reserved_grams), 0)

  const columns: Column<GoldWalletDTO>[] = [
    {
      key: "customer",
      header: i18n.t('app.admin.gold-wallet.page.text_1'),
      cell: (r) => (
        <div className="flex items-center gap-2.5">
          <AvatarBadge name={(r as any).customer_name || "—"} size="sm" variant="gold" />
          <span className="text-[13px] font-medium">{(r as any).customer_name || "—"}</span>
        </div>
      ),
    },
    { key: "wallet", header: i18n.t('app.admin.gold-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.gold-wallet.page.text_3'), cell: (r) => <span className="font-mono tabular-nums text-[13px] font-semibold">{fmtGrams(r.available_grams)}</span> },
    {
      key: "held",
      header: i18n.t('app.admin.gold-wallet.page.text_4'),
      cell: (r) => <span className={`font-mono tabular-nums text-[13px] ${Number(r.reserved_grams) > 0 ? "text-amber-600 font-semibold" : "text-muted-foreground"}`}>{fmtGrams(r.reserved_grams)}</span>,
    },
    {
      key: "oz",
      header: i18n.t('app.admin.gold-wallet.page.text_5'),
      cell: (r) => <span className="font-mono tabular-nums text-[12.5px] text-muted-foreground">{fmtOunces(Number(r.available_grams) * OZ_PER_GRAM)}</span>,
    },
  ]

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

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.gold-wallet.page.text_10')} value={fmtGrams(totalG)} icon={Coins} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.gold-wallet.page.text_11')} value={fmtOunces(totalG * OZ_PER_GRAM)} icon={Scale} tone="gold" />
        <KpiCard label={i18n.t('app.admin.gold-wallet.page.text_12')} value={fmtGrams(heldG)} icon={ShieldCheck} tone="warning" />
        <KpiCard label={i18n.t('app.admin.gold-wallet.page.text_13')} value={fmtMoney(totalG * GRAM_PRICE_USD)} icon={Sparkles} tone="success" />
      </div>

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

        <div className="grid gap-6 lg:grid-cols-[1fr_400px]">
        <SectionCard title={i18n.t('app.admin.gold-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.gold-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.gold-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.gold-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 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.gold-wallet.page.text_29')}</span>
                  <span className="font-mono text-[20px] font-bold tabular-nums text-gold-700">{fmtGrams(selected.available_grams)}</span>
                </div>
                <div className="flex items-baseline justify-between border-t border-gold-200/60 pt-2.5">
                  <span className="text-[11.5px] uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.gold-wallet.page.text_30')}</span>
                  <span className="font-mono text-[15px] font-semibold tabular-nums">{fmtOunces(Number(selected.available_grams) * OZ_PER_GRAM)}</span>
                </div>
                <div className="flex items-baseline justify-between border-t border-gold-200/60 pt-2.5">
                  <span className="text-[11.5px] uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.gold-wallet.page.text_31')}</span>
                  <span className="font-mono text-[14px] font-bold tabular-nums">{selected.purity_name_ar} {selected.karat}k</span>
                </div>
              </div>
              <div className="rounded-lg border border-border bg-muted/30 p-3 space-y-2">
                <div className="flex items-center justify-between text-[12.5px]">
                  <span className="text-muted-foreground">{i18n.t('app.admin.gold-wallet.page.text_32')}</span>
                  <span className="font-mono font-semibold tabular-nums">{fmtMoney(Number(selected.available_grams) * GRAM_PRICE_USD)}</span>
                </div>
                <div className="flex items-center justify-between text-[12.5px]">
                  <span className="text-muted-foreground">{i18n.t('app.admin.gold-wallet.page.text_33')}</span>
                  <span className="font-mono tabular-nums">{fmtMoney(GRAM_PRICE_USD)}</span>
                </div>
              </div>
              <div>
                <p className="text-[12px] font-semibold uppercase tracking-wide text-muted-foreground mb-2.5">{i18n.t('app.admin.gold-wallet.page.text_34')}</p>
                {movements.length === 0 ? (
                  <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.gold-wallet.page.text_35')}</p>
                ) : (
                  <div className="space-y-2 max-h-[250px] 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-gold-50 text-gold-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.gold-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-gold-600" : "text-red-600"}`}>
                            {m.direction === "credit" ? "+" : "−"}
                            {fmtGrams(m.grams)}
                          </span>
                          <span className="text-[10px] text-muted-foreground font-mono">{i18n.t('app.admin.gold-wallet.page.text_36')}{fmtGrams(m.balance_after)}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ) : (
            <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.gold-wallet.page.text_39')}</p>
          )}
        </SectionCard>
      </div>
      </div>

      <Modal
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={opType === "deposit" ? i18n.t('app.admin.gold-wallet.page.text_18') : i18n.t('app.admin.gold-wallet.page.text_19')}
        description={i18n.t('app.admin.wallets.page.text_operation', { opType: opType === "deposit" ? i18n.t('app.admin.gold-wallet.page.text_20') : i18n.t('app.admin.gold-wallet.page.text_21'), customer_name: (selected as any)?.customer_name })}
        size="sm"
      >
        <form onSubmit={onSubmit} className="space-y-4">
          <InputField
            id="grams"
            name="grams"
            label={i18n.t('app.admin.gold-wallet.page.text_22')}
            type="number"
            value={grams}
            onChange={(e) => setGrams(e.target.value)}
            placeholder="0.00"
            required
          />
          <InputField
            id="description"
            name="description"
            label={i18n.t('app.admin.gold-wallet.page.text_23')}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder={i18n.t('app.admin.gold-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.gold-wallet.page.text_40')}</Button>
              <Button type="submit" isLoading={isSubmitting}>{opType === "deposit" ? i18n.t('app.admin.gold-wallet.page.text_25') : i18n.t('app.admin.gold-wallet.page.text_26')}</Button>
            </ModalActions>
          </div>
        </form>
      </Modal>
    </div>
  )
}
