'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { apiRequest, getCurrentUser, idempotencyKey } from '../../../lib/api';
import { getPublicConfig } from '../../../lib/publicConfig';
import { requireAuth } from '../../../lib/authRedirect';
import { Button } from '../../../components/Button';
import { CoinAmount } from '../../../components/CoinAmount';
import { PageHeader } from '../../../components/PageHeader';
import { EmptyBlock, ErrorBlock, LoadingBlock } from '../../../components/StateBlock';

export default function WalletPage() {
  const router = useRouter();
  const pathname = usePathname();
  const [data, setData] = useState<any>(null);
  const [withdrawals, setWithdrawals] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [amount, setAmount] = useState(100);
  const [upiId, setUpiId] = useState('');
  const [busy, setBusy] = useState(false);
  const [depositEnabled, setDepositEnabled] = useState(true);
  const [depositNotice, setDepositNotice] = useState('');
  const [kycOk, setKycOk] = useState(true);

  const load = async () => {
    if (requireAuth(router, pathname || '/wallet')) return;
    setLoading(true);
    try {
      const [res, w, cfg, kyc] = await Promise.all([
        apiRequest('/wallet'),
        apiRequest('/wallet/withdrawals'),
        getPublicConfig(),
        apiRequest('/kyc/my-status').catch(() => ({ data: null })),
      ]);
      setData(res.data);
      setWithdrawals(w.data || []);
      setDepositEnabled(cfg.data?.deposit?.enabled !== false);
      setDepositNotice(cfg.data?.deposit?.notice || '');
      const st = String(kyc.data?.status || '').toUpperCase();
      setKycOk(st === 'APPROVED' || st === 'VERIFIED');
      setError('');
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const deposit = async () => {
    setBusy(true);
    setError('');
    try {
      await apiRequest('/wallet/deposit', {
        method: 'POST',
        idempotencyKey: idempotencyKey('dep'),
        body: JSON.stringify({ amount, paymentReference: `MANUAL-${Date.now()}` }),
      });
      window.dispatchEvent(new Event('my11s:coins'));
      await load();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  };

  const withdraw = async () => {
    const upi = upiId.trim();
    if (!upi || !upi.includes('@')) {
      setError('Enter a valid UPI ID (e.g. name@upi).');
      return;
    }
    if (!kycOk) {
      setError('Complete KYC before withdrawing.');
      return;
    }
    setBusy(true);
    setError('');
    try {
      await apiRequest('/wallet/withdraw', {
        method: 'POST',
        idempotencyKey: idempotencyKey('wd'),
        body: JSON.stringify({
          amount: Math.max(100, amount),
          payoutMethod: 'UPI',
          upiId: upi,
        }),
      });
      window.dispatchEvent(new Event('my11s:coins'));
      setUpiId('');
      await load();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  };

  if (loading) return <LoadingBlock label="Loading wallet…" />;

  const w = data?.wallet;

  return (
    <div className="app-page">
      <PageHeader title="Wallet" backHref="/profile" backLabel="Account" />

      <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-d11-navy via-[#1c1e2e] to-[#2a1830] p-5 text-white shadow-lift">
        <div
          className="pointer-events-none absolute -right-8 -top-10 h-36 w-36 rounded-full bg-d11-red/25 blur-2xl"
          aria-hidden
        />
        <div
          className="pointer-events-none absolute -bottom-10 left-8 h-28 w-28 rounded-full bg-amber-400/15 blur-2xl"
          aria-hidden
        />
        <p className="relative text-[10px] font-bold uppercase tracking-[0.16em] text-white/55">Total coins</p>
        <p className="relative mt-1 font-display text-3xl font-extrabold tracking-tight">
          {w ? <CoinAmount amount={w.totalBalance} iconClassName="h-7 w-7 text-amber-300" /> : '—'}
        </p>
        <div className="relative mt-4 grid grid-cols-3 gap-2 text-center">
          {[
            ['Deposit', w?.depositBalance],
            ['Winnings', w?.winningBalance],
            ['Bonus', w?.bonusBalance],
          ].map(([l, v]) => (
            <div key={l as string} className="rounded-xl bg-white/10 px-2 py-2.5 ring-1 ring-white/10 backdrop-blur-sm">
              <div className="text-[9px] font-bold uppercase tracking-wide text-white/50">{l}</div>
              <div className="mt-0.5 justify-center text-xs font-bold">
                <CoinAmount amount={v as number} iconClassName="h-3 w-3 text-amber-300" />
              </div>
            </div>
          ))}
        </div>
      </div>

      {error && <ErrorBlock message={error} onRetry={load} />}

      {!kycOk && (
        <div className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3.5 text-sm text-amber-900">
          Complete KYC to withdraw winnings.{' '}
          <Link href="/kyc" className="font-bold underline">
            Verify now
          </Link>
        </div>
      )}

      {!w ? (
        <EmptyBlock title="Wallet unavailable" hint="Try again in a moment." />
      ) : (
        <div className="d11-card space-y-3.5 p-4 sm:p-5">
          {depositNotice && (
            <div className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
              {depositNotice}
            </div>
          )}
          <label className="block text-[11px] font-bold uppercase text-d11-muted">
            Coins
            <input
              type="number"
              min={10}
              inputMode="numeric"
              value={amount}
              onChange={(e) => setAmount(Number(e.target.value))}
              className="d11-input mt-1.5"
              disabled={!depositEnabled}
            />
          </label>
          <label className="block text-[11px] font-bold uppercase text-d11-muted">
            UPI ID (for withdraw)
            <input
              type="text"
              inputMode="email"
              autoComplete="off"
              placeholder="name@upi"
              value={upiId}
              onChange={(e) => setUpiId(e.target.value)}
              className="d11-input mt-1.5"
            />
          </label>
          <div className="grid grid-cols-2 gap-2">
            <Button loading={busy} onClick={deposit} disabled={!depositEnabled}>
              {depositEnabled ? 'Add coins' : 'Deposits off'}
            </Button>
            <Button variant="outline" loading={busy} onClick={withdraw} disabled={!kycOk}>
              Withdraw
            </Button>
          </div>
          <p className="text-[11px] text-d11-muted">
            {depositEnabled
              ? 'Deposits stay pending until payment is confirmed. Min withdraw 100 coins.'
              : 'Deposits are currently disabled by admin.'}
          </p>
        </div>
      )}

      <section className="space-y-2.5">
        <h2 className="app-section-title">Withdrawals</h2>
        {!withdrawals.length ? (
          <EmptyBlock title="No withdrawal requests yet." />
        ) : (
          withdrawals.map((row) => (
            <div key={row._id} className="d11-card flex justify-between px-4 py-3 text-sm">
              <div>
                <div className="font-bold text-d11-ink">
                  <CoinAmount amount={row.amount} />
                </div>
                <div className="text-[11px] text-d11-muted">
                  {row.payoutMethod}
                  {row.upiId ? ` · ${row.upiId}` : ''}
                </div>
              </div>
              <span className="text-xs font-bold uppercase text-d11-red">{row.status}</span>
            </div>
          ))
        )}
      </section>
    </div>
  );
}
