'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import TransactionRow from '@/components/leagues/TransactionRow';
import { useInject } from '@/lib/di/hooks/useInject';
import { LEAGUE_WALLET_SERVICE_TOKEN } from '@/lib/di/tokens';
import { LeagueWalletViewModel } from '@/lib/view-models/LeagueWalletViewModel';
import {
  Wallet,
  DollarSign,
  ArrowUpRight,
  Clock,
  AlertTriangle,
  Download,
  TrendingUp
} from 'lucide-react';


export default function LeagueWalletPage() {
  const params = useParams();
  const leagueWalletService = useInject(LEAGUE_WALLET_SERVICE_TOKEN);
  const [wallet, setWallet] = useState<LeagueWalletViewModel | null>(null);
  const [withdrawAmount, setWithdrawAmount] = useState('');
  const [showWithdrawModal, setShowWithdrawModal] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [filterType, setFilterType] = useState<'all' | 'sponsorship' | 'membership' | 'withdrawal' | 'prize'>('all');

  useEffect(() => {
    const loadWallet = async () => {
      if (params.id) {
        try {
          const walletData = await leagueWalletService.getWalletForLeague(params.id as string);
          setWallet(walletData);
        } catch (error) {
          console.error('Failed to load wallet:', error);
        }
      }
    };
    loadWallet();
  }, [params.id, leagueWalletService]);

  if (!wallet) {
    return <div>Loading...</div>;
  }

  const filteredTransactions = wallet.getFilteredTransactions(filterType);

  const handleWithdraw = async () => {
    if (!withdrawAmount || parseFloat(withdrawAmount) <= 0) return;

    setProcessing(true);
    try {
      const result = await leagueWalletService.withdraw(
        params.id as string,
        parseFloat(withdrawAmount),
        wallet.currency,
        'season-2', // Current active season
        'bank-account-***1234'
      );

      if (!result.success) {
        alert(result.message || 'Withdrawal failed');
        return;
      }

      alert(`Withdrawal of $${withdrawAmount} processed successfully!`);
      setShowWithdrawModal(false);
      setWithdrawAmount('');
      // Refresh wallet data
      const updatedWallet = await leagueWalletService.getWalletForLeague(params.id as string);
      setWallet(updatedWallet);
    } catch (err) {
      console.error('Withdrawal error:', err);
      alert('Failed to process withdrawal');
    } finally {
      setProcessing(false);
    }
  };

  return (
    <div className="max-w-6xl mx-auto py-8 px-4">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-white">League Wallet</h1>
          <p className="text-gray-400">Manage your league's finances and payouts</p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="secondary">
            <Download className="w-4 h-4 mr-2" />
            Export
          </Button>
          <Button
            variant="primary"
            onClick={() => setShowWithdrawModal(true)}
            disabled={!wallet.canWithdraw}
          >
            <ArrowUpRight className="w-4 h-4 mr-2" />
            Withdraw
          </Button>
        </div>
      </div>

      {/* Withdrawal Warning */}
      {!wallet.canWithdraw && wallet.withdrawalBlockReason && (
        <div className="mb-6 p-4 rounded-lg bg-warning-amber/10 border border-warning-amber/30">
          <div className="flex items-start gap-3">
            <AlertTriangle className="w-5 h-5 text-warning-amber shrink-0 mt-0.5" />
            <div>
              <h3 className="font-medium text-warning-amber">Withdrawals Temporarily Unavailable</h3>
              <p className="text-sm text-gray-400 mt-1">{wallet.withdrawalBlockReason}</p>
            </div>
          </div>
        </div>
      )}

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-performance-green/10">
              <Wallet className="w-6 h-6 text-performance-green" />
            </div>
            <div>
              <div className="text-2xl font-bold text-white">{wallet.formattedBalance}</div>
              <div className="text-sm text-gray-400">Available Balance</div>
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary-blue/10">
              <TrendingUp className="w-6 h-6 text-primary-blue" />
            </div>
            <div>
              <div className="text-2xl font-bold text-white">{wallet.formattedTotalRevenue}</div>
              <div className="text-sm text-gray-400">Total Revenue</div>
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-warning-amber/10">
              <DollarSign className="w-6 h-6 text-warning-amber" />
            </div>
            <div>
              <div className="text-2xl font-bold text-white">{wallet.formattedTotalFees}</div>
              <div className="text-sm text-gray-400">Platform Fees (10%)</div>
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-purple-500/10">
              <Clock className="w-6 h-6 text-purple-400" />
            </div>
            <div>
              <div className="text-2xl font-bold text-white">{wallet.formattedPendingPayouts}</div>
              <div className="text-sm text-gray-400">Pending Payouts</div>
            </div>
          </div>
        </Card>
      </div>

      {/* Transactions */}
      <Card>
        <div className="flex items-center justify-between p-4 border-b border-charcoal-outline">
          <h2 className="text-lg font-semibold text-white">Transaction History</h2>
          <select
            value={filterType}
            onChange={(e) => setFilterType(e.target.value as typeof filterType)}
            className="px-3 py-1.5 rounded-lg border border-charcoal-outline bg-iron-gray text-white text-sm focus:border-primary-blue focus:outline-none"
          >
            <option value="all">All Transactions</option>
            <option value="sponsorship">Sponsorships</option>
            <option value="membership">Memberships</option>
            <option value="withdrawal">Withdrawals</option>
            <option value="prize">Prizes</option>
          </select>
        </div>

        {filteredTransactions.length === 0 ? (
          <div className="text-center py-12">
            <Wallet className="w-12 h-12 text-gray-500 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-white mb-2">No Transactions</h3>
            <p className="text-gray-400">
              {filterType === 'all' 
                ? 'Revenue from sponsorships and fees will appear here.'
                : `No ${filterType} transactions found.`}
            </p>
          </div>
        ) : (
          <div>
            {filteredTransactions.map((transaction) => (
              <TransactionRow key={transaction.id} transaction={transaction} />
            ))}
          </div>
        )}
      </Card>

      {/* Revenue Breakdown */}
      <div className="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card className="p-4">
          <h3 className="text-lg font-semibold text-white mb-4">Revenue Breakdown</h3>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-primary-blue" />
                <span className="text-gray-400">Sponsorships</span>
              </div>
              <span className="font-medium text-white">$1,600.00</span>
            </div>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-performance-green" />
                <span className="text-gray-400">Membership Fees</span>
              </div>
              <span className="font-medium text-white">$1,600.00</span>
            </div>
            <div className="flex items-center justify-between pt-2 border-t border-charcoal-outline">
              <span className="text-gray-300 font-medium">Total Gross Revenue</span>
              <span className="font-bold text-white">$3,200.00</span>
            </div>
            <div className="flex items-center justify-between text-sm">
              <span className="text-warning-amber">Platform Fee (10%)</span>
              <span className="text-warning-amber">-$320.00</span>
            </div>
            <div className="flex items-center justify-between pt-2 border-t border-charcoal-outline">
              <span className="text-performance-green font-medium">Net Revenue</span>
              <span className="font-bold text-performance-green">$2,880.00</span>
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <h3 className="text-lg font-semibold text-white mb-4">Payout Schedule</h3>
          <div className="space-y-3">
            <div className="p-3 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm font-medium text-white">Season 2 Prize Pool</span>
                <span className="text-sm font-medium text-warning-amber">Pending</span>
              </div>
              <p className="text-xs text-gray-500">
                Distributed after season completion to top 3 drivers
              </p>
            </div>
            <div className="p-3 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm font-medium text-white">Available for Withdrawal</span>
                <span className="text-sm font-medium text-performance-green">{wallet.formattedBalance}</span>
              </div>
              <p className="text-xs text-gray-500">
                Available after Season 2 ends (estimated: Jan 15, 2026)
              </p>
            </div>
          </div>
        </Card>
      </div>

      {/* Withdraw Modal */}
      {showWithdrawModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <Card className="w-full max-w-md p-6">
            <h2 className="text-xl font-semibold text-white mb-4">Withdraw Funds</h2>
            
            {!wallet.canWithdraw ? (
              <div className="p-4 rounded-lg bg-warning-amber/10 border border-warning-amber/30 mb-4">
                <p className="text-sm text-warning-amber">{wallet.withdrawalBlockReason}</p>
              </div>
            ) : (
              <>
                <div className="mb-4">
                  <label className="block text-sm font-medium text-gray-300 mb-2">
                    Amount to Withdraw
                  </label>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
                    <input
                      type="number"
                      value={withdrawAmount}
                      onChange={(e) => setWithdrawAmount(e.target.value)}
                      max={wallet.balance}
                      className="w-full pl-8 pr-4 py-2 rounded-lg border border-charcoal-outline bg-iron-gray text-white focus:border-primary-blue focus:outline-none"
                      placeholder="0.00"
                    />
                  </div>
                  <p className="text-xs text-gray-500 mt-1">
                    Available: {wallet.formattedBalance}
                  </p>
                </div>

                <div className="mb-4">
                  <label className="block text-sm font-medium text-gray-300 mb-2">
                    Destination
                  </label>
                  <select className="w-full px-3 py-2 rounded-lg border border-charcoal-outline bg-iron-gray text-white focus:border-primary-blue focus:outline-none">
                    <option>Bank Account ***1234</option>
                  </select>
                </div>
              </>
            )}

            <div className="flex gap-3 mt-6">
              <Button
                variant="secondary"
                onClick={() => setShowWithdrawModal(false)}
                className="flex-1"
              >
                Cancel
              </Button>
              <Button
                variant="primary"
                onClick={handleWithdraw}
                disabled={!wallet.canWithdraw || processing || !withdrawAmount}
                className="flex-1"
              >
                {processing ? 'Processing...' : 'Withdraw'}
              </Button>
            </div>
          </Card>
        </div>
      )}

      {/* Alpha Notice */}
      <div className="mt-6 rounded-lg bg-warning-amber/10 border border-warning-amber/30 p-4">
        <p className="text-xs text-gray-400">
          <strong className="text-warning-amber">Alpha Note:</strong> Wallet management is demonstration-only.
          Real payment processing and bank integrations will be available when the payment system is fully implemented.
          The 10% platform fee and season-based withdrawal restrictions are enforced in the actual implementation.
        </p>
      </div>
    </div>
  );
}