'use client';

import React, { useState, useEffect } from 'react';
import Sidebar from '@/components/dashboard/Sidebar';
import Header from '@/components/dashboard/Header';
import {
  Wallet,
  Plus,
  ArrowDownLeft,
  ArrowUpRight,
  Receipt,
  Download,
  CreditCard,
  CheckCircle2,
  RefreshCw,
  X,
  Check,
  ShieldCheck,
} from 'lucide-react';

export default function WalletBillingPage() {
  const [user, setUser] = useState<any>(null);
  const [wallet, setWallet] = useState<any>(null);
  const [transactions, setTransactions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // Top Up Modal
  const [topUpModalOpen, setTopUpModalOpen] = useState(false);
  const [topUpAmount, setTopUpAmount] = useState('20000');
  const [funding, setFunding] = useState(false);
  const [fundSuccess, setFundSuccess] = useState(false);

  const fetchWalletData = async () => {
    try {
      const [accRes, txRes] = await Promise.all([
        fetch('/api/v1/account'),
        fetch('/api/v1/transactions?limit=50'),
      ]);
      const accData = await accRes.json();
      const txData = await txRes.json();

      if (accData.success) {
        setUser(accData.data.user);
        setWallet(accData.data.wallet);
      }
      if (txData.success) {
        setTransactions(txData.data.transactions || []);
      }
    } catch {}
    finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchWalletData();
  }, []);

  const handleTopUp = async () => {
    setFunding(true);
    try {
      const res = await fetch('/api/v1/wallet', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount: parseFloat(topUpAmount) }),
      });
      const data = await res.json();
      if (data.success) {
        setFundSuccess(true);
        fetchWalletData();
        setTimeout(() => {
          setFundSuccess(false);
          setTopUpModalOpen(false);
        }, 1200);
      }
    } catch {
    } finally {
      setFunding(false);
    }
  };

  return (
    <div className="flex min-h-screen bg-[#070b14] text-slate-100">
      <Sidebar userRole={user?.role} />

      <div className="flex-1 flex flex-col min-w-0">
        <Header user={user} walletBalance={wallet?.balance || 0} onRefreshWallet={fetchWalletData} />

        <main className="flex-1 p-6 space-y-6 overflow-y-auto max-w-7xl">
          {/* Header */}
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div>
              <h1 className="text-xl font-bold text-white flex items-center gap-2">
                <Wallet className="w-5 h-5 text-emerald-400" />
                Wallet & Billing Engine
              </h1>
              <p className="text-xs text-slate-400 mt-0.5">
                Manage your verification credit balance, billing history, and pricing breakdown.
              </p>
            </div>

            <button
              onClick={() => setTopUpModalOpen(true)}
              className="px-4 py-2 bg-emerald-400 hover:bg-emerald-300 text-slate-900 font-bold text-xs rounded-xl shadow-md shadow-emerald-500/20 transition-all flex items-center gap-2"
            >
              <Plus className="w-4 h-4" />
              Add Test Funds
            </button>
          </div>

          {/* 3 Top Cards: Balance, Estimated Calls, Billing Policy */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* Wallet Balance Card */}
            <div className="glass-panel p-6 rounded-2xl border border-slate-700/80 bg-gradient-to-br from-slate-900/90 to-[#070b14] space-y-3 relative overflow-hidden">
              <div className="flex items-center justify-between text-slate-400">
                <span className="text-xs font-bold uppercase tracking-wider">Available Balance</span>
                <span className="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 text-[10px] font-mono font-bold">
                  NGN
                </span>
              </div>
              <div className="text-3xl font-extrabold text-white font-mono">
                ₦{(wallet?.balance || 0).toLocaleString()}
              </div>
              <div className="pt-2 text-xs text-slate-400">
                ~ {Math.floor((wallet?.balance || 0) / 100).toLocaleString()} NIN verifications remaining
              </div>
            </div>

            {/* Pricing Rates Card */}
            <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-3">
              <span className="text-xs font-bold uppercase tracking-wider text-slate-400 block">
                Standard Pricing Rates
              </span>
              <div className="space-y-2 text-xs">
                <div className="flex justify-between items-center">
                  <span className="text-slate-300">NIN Verification:</span>
                  <span className="font-bold text-emerald-400 font-mono">₦100.00 / call</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-slate-300">Phone-NIN Match:</span>
                  <span className="font-bold text-teal-400 font-mono">₦80.00 / call</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-slate-300">BVN Mock Lookup:</span>
                  <span className="font-bold text-cyan-400 font-mono">₦120.00 / call</span>
                </div>
              </div>
            </div>

            {/* Fair Billing Guarantee */}
            <div className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-3">
              <div className="flex items-center gap-2 text-emerald-400">
                <ShieldCheck className="w-5 h-5" />
                <span className="text-xs font-bold uppercase tracking-wider text-white">Fair Billing Policy</span>
              </div>
              <p className="text-xs text-slate-400 leading-relaxed">
                You are strictly billed for confirmed verifications only. Upstream timeouts, non-existent records, and network dropouts incur zero charge.
              </p>
            </div>
          </div>

          {/* Transactions Ledger */}
          <div className="glass-panel rounded-2xl p-6 border border-slate-800 space-y-4">
            <div className="flex items-center justify-between border-b border-slate-800 pb-3">
              <h3 className="text-sm font-bold text-white flex items-center gap-2">
                <Receipt className="w-4 h-4 text-emerald-400" />
                Transaction Statement
              </h3>
              <span className="text-xs text-slate-400 font-mono">
                {transactions.length} Total Records
              </span>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs font-mono">
                <thead>
                  <tr className="border-b border-slate-800 text-slate-400 text-[11px]">
                    <th className="py-3 px-3">Reference ID</th>
                    <th className="py-3 px-3">Type</th>
                    <th className="py-3 px-3">Description</th>
                    <th className="py-3 px-3">Amount</th>
                    <th className="py-3 px-3">Status</th>
                    <th className="py-3 px-3">Date</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60 text-slate-300">
                  {transactions.length > 0 ? (
                    transactions.map((tx) => (
                      <tr key={tx.id} className="hover:bg-slate-900/40 transition-colors">
                        <td className="py-3 px-3 font-bold text-white">{tx.referenceId}</td>
                        <td className="py-3 px-3">
                          <span
                            className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold ${
                              tx.type === 'CREDIT'
                                ? 'bg-emerald-500/20 text-emerald-300'
                                : 'bg-slate-800 text-slate-300'
                            }`}
                          >
                            {tx.type === 'CREDIT' ? (
                              <ArrowDownLeft className="w-3 h-3 text-emerald-400" />
                            ) : (
                              <ArrowUpRight className="w-3 h-3 text-slate-400" />
                            )}
                            {tx.type}
                          </span>
                        </td>
                        <td className="py-3 px-3 font-sans text-slate-300">{tx.description}</td>
                        <td className="py-3 px-3 font-bold text-white">
                          <span className={tx.type === 'CREDIT' ? 'text-emerald-400' : 'text-slate-300'}>
                            {tx.type === 'CREDIT' ? '+' : '-'}₦{tx.amount.toLocaleString()}
                          </span>
                        </td>
                        <td className="py-3 px-3">
                          <span className="px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-300 text-[10px] font-bold">
                            {tx.status}
                          </span>
                        </td>
                        <td className="py-3 px-3 text-slate-400 font-sans">
                          {new Date(tx.createdAt).toLocaleString()}
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={6} className="py-6 text-center text-slate-500 font-sans">
                        {loading ? 'Loading ledger records...' : 'No transactions recorded yet.'}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          {/* Top Up Modal */}
          {topUpModalOpen && (
            <div className="fixed inset-0 bg-black/75 backdrop-blur-sm z-50 flex items-center justify-center p-4">
              <div className="glass-panel w-full max-w-md rounded-2xl p-6 border border-slate-700 space-y-5 shadow-2xl animate-in fade-in zoom-in-95 duration-200">
                <div className="flex items-center justify-between border-b border-slate-800 pb-3">
                  <div className="flex items-center gap-2">
                    <Wallet className="w-5 h-5 text-emerald-400" />
                    <h3 className="text-base font-bold text-white">Fund Sandbox Wallet</h3>
                  </div>
                  <button
                    onClick={() => setTopUpModalOpen(false)}
                    className="text-slate-400 hover:text-white p-1"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>

                <p className="text-xs text-slate-300">
                  Select an amount to simulate funding your developer wallet instantly.
                </p>

                <div className="space-y-3">
                  <label className="block text-xs font-semibold text-slate-300">Preset Amount (NGN)</label>
                  <div className="grid grid-cols-3 gap-2">
                    {['10000', '25000', '50000'].map((amt) => (
                      <button
                        key={amt}
                        type="button"
                        onClick={() => setTopUpAmount(amt)}
                        className={`py-2 px-3 rounded-xl border text-xs font-mono font-bold transition-all ${
                          topUpAmount === amt
                            ? 'bg-emerald-500/20 text-emerald-300 border-emerald-500'
                            : 'bg-slate-900/80 text-slate-300 border-slate-800 hover:border-slate-700'
                        }`}
                      >
                        ₦{parseInt(amt).toLocaleString()}
                      </button>
                    ))}
                  </div>

                  <div>
                    <label className="block text-xs font-semibold text-slate-300 mb-1">Custom Amount</label>
                    <input
                      type="number"
                      value={topUpAmount}
                      onChange={(e) => setTopUpAmount(e.target.value)}
                      className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3.5 py-2 text-xs font-mono text-white focus:outline-none focus:border-emerald-500"
                    />
                  </div>
                </div>

                <div className="pt-2">
                  <button
                    onClick={handleTopUp}
                    disabled={funding || fundSuccess}
                    className="w-full py-3 bg-emerald-400 hover:bg-emerald-300 text-slate-900 font-bold text-xs rounded-xl shadow-lg shadow-emerald-500/20 transition-all flex items-center justify-center gap-2 disabled:opacity-50"
                  >
                    {funding ? (
                      <RefreshCw className="w-4 h-4 animate-spin" />
                    ) : fundSuccess ? (
                      <Check className="w-4 h-4 text-slate-900" />
                    ) : (
                      <Plus className="w-4 h-4" />
                    )}
                    {funding
                      ? 'Crediting Wallet...'
                      : fundSuccess
                      ? 'Wallet Funded Successfully!'
                      : `Credit ₦${parseFloat(topUpAmount || '0').toLocaleString()} to Wallet`}
                  </button>
                </div>
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
