'use client';

import React, { useEffect, useState } from 'react';
import { Wallet, ArrowDownRight, ArrowUpRight, ShieldAlert, Check, X } from 'lucide-react';
import { formatCoins } from '../../../lib/coins';
import { apiRequest } from '../../../lib/api';
import { Badge } from '../../../components/Badge';
import { Button } from '../../../components/Button';
import { Modal } from '../../../components/Modal';

export default function WalletAdminPage() {
  const [withdrawals, setWithdrawals] = useState<any[]>([]);
  const [users, setUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isAdjustOpen, setIsAdjustOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const [adjustForm, setAdjustForm] = useState({
    userId: '',
    amount: 100,
    balanceType: 'deposit',
    reason: '',
  });

  const loadData = async () => {
    try {
      setLoading(true);
      const [wRes, uRes] = await Promise.all([
        apiRequest('/wallet/admin/withdrawals'),
        apiRequest('/users?role=CUSTOMER'),
      ]);
      setWithdrawals(wRes.data || []);
      setUsers(uRes.data || []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const handleAdjust = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const idempotencyKey = `admin-adj-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
      await apiRequest('/wallet/admin/adjust', {
        method: 'POST',
        idempotencyKey,
        body: JSON.stringify(adjustForm),
      });
      setIsAdjustOpen(false);
      setAdjustForm({ userId: '', amount: 100, balanceType: 'deposit', reason: '' });
      alert('Wallet adjustment successfully applied and recorded to immutable ledger.');
      loadData();
    } catch (err: any) {
      alert(err.message || 'Failed to adjust wallet');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-white">Wallet & Ledger Operations</h1>
          <p className="text-xs text-zinc-400 mt-1">
            Authoritative double-entry ledger inspects, withdrawal processing, and audited manual adjustments
          </p>
        </div>
        <Button onClick={() => setIsAdjustOpen(true)} className="gap-2" variant="amber">
          <ShieldAlert className="w-4 h-4" />
          <span>Manual Balance Adjustment</span>
        </Button>
      </div>

      {/* Withdrawal Requests Section */}
      <div className="bg-zinc-900/80 border border-zinc-800 rounded-2xl p-6">
        <h2 className="text-base font-bold text-white mb-4">Pending & Recent Withdrawal Requests</h2>
        {loading ? (
          <div className="py-8 text-center text-xs text-zinc-400">Loading withdrawals...</div>
        ) : withdrawals.length === 0 ? (
          <div className="py-8 text-center text-xs text-zinc-400">No withdrawal requests found.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead className="text-[11px] font-semibold text-zinc-400 uppercase tracking-wider border-b border-zinc-800 pb-2">
                <tr>
                  <th className="pb-3">User</th>
                  <th className="pb-3">Amount</th>
                  <th className="pb-3">Method</th>
                  <th className="pb-3">Details</th>
                  <th className="pb-3">Requested</th>
                  <th className="pb-3">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-zinc-800/60 font-mono text-xs">
                {withdrawals.map((w) => (
                  <tr key={w._id} className="hover:bg-zinc-800/30 transition-colors">
                    <td className="py-3.5 font-sans font-medium text-white">
                      {w.userId?.name}
                      <div className="text-[11px] text-zinc-400 font-mono">{w.userId?.phone}</div>
                    </td>
                    <td className="py-3.5 text-rose-400 font-bold">{formatCoins(w.amount)}</td>
                    <td className="py-3.5 font-sans text-zinc-300">{w.payoutMethod}</td>
                    <td className="py-3.5 text-zinc-400 font-sans">
                      {w.payoutMethod === 'UPI'
                        ? w.upiId
                        : `${w.bankDetails?.accountNumber} (${w.bankDetails?.ifsc})`}
                    </td>
                    <td className="py-3.5 text-zinc-400">
                      {new Date(w.createdAt).toLocaleDateString()}
                    </td>
                    <td className="py-3.5 font-sans">
                      <Badge
                        variant={
                          w.status === 'PROCESSED'
                            ? 'emerald'
                            : w.status === 'REJECTED'
                            ? 'rose'
                            : 'amber'
                        }
                      >
                        {w.status}
                      </Badge>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Manual Adjustment Modal */}
      <Modal
        isOpen={isAdjustOpen}
        onClose={() => setIsAdjustOpen(false)}
        title="Audited Balance Adjustment"
      >
        <form onSubmit={handleAdjust} className="space-y-4 text-xs">
          <div className="p-3 bg-amber-950/40 border border-amber-800/50 rounded-xl text-amber-300 text-xs">
            Notice: All manual balance modifications are strictly audited with immutable ledger entries and require a documented business reason.
          </div>

          <div>
            <label className="block text-zinc-300 uppercase font-semibold mb-1">Select User</label>
            <select
              required
              value={adjustForm.userId}
              onChange={(e) => setAdjustForm({ ...adjustForm, userId: e.target.value })}
              className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white"
            >
              <option value="">Choose User</option>
              {users.map((u) => (
                <option key={u._id} value={u._id}>
                  {u.name} ({u.phone})
                </option>
              ))}
            </select>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-zinc-300 uppercase font-semibold mb-1">
                Adjustment Amount (₹)
              </label>
              <input
                type="number"
                required
                value={adjustForm.amount}
                onChange={(e) => setAdjustForm({ ...adjustForm, amount: parseFloat(e.target.value) })}
                className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white font-mono"
                placeholder="Use negative for debit"
              />
            </div>
            <div>
              <label className="block text-zinc-300 uppercase font-semibold mb-1">Bucket Type</label>
              <select
                value={adjustForm.balanceType}
                onChange={(e) => setAdjustForm({ ...adjustForm, balanceType: e.target.value })}
                className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white"
              >
                <option value="deposit">Deposit Balance</option>
                <option value="winning">Winning Balance</option>
                <option value="bonus">Bonus Balance</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-zinc-300 uppercase font-semibold mb-1">
              Required Reason (Minimum 5 characters)
            </label>
            <textarea
              required
              minLength={5}
              rows={3}
              placeholder="e.g. Compensation for tournament technical delay or promotional award"
              value={adjustForm.reason}
              onChange={(e) => setAdjustForm({ ...adjustForm, reason: e.target.value })}
              className="w-full px-3 py-2 bg-zinc-950 border border-zinc-800 rounded-lg text-white"
            />
          </div>

          <div className="pt-2 flex justify-end gap-2">
            <Button type="button" variant="secondary" onClick={() => setIsAdjustOpen(false)}>
              Cancel
            </Button>
            <Button type="submit" variant="amber" loading={submitting}>
              Apply & Audit
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
