'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 { 
  Wallet, 
  DollarSign, 
  ArrowUpRight, 
  ArrowDownLeft, 
  Clock,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Download,
  CreditCard,
  TrendingUp,
  Calendar
} from 'lucide-react';

interface Transaction {
  id: string;
  type: 'sponsorship' | 'membership' | 'withdrawal' | 'prize';
  description: string;
  amount: number;
  fee: number;
  netAmount: number;
  date: Date;
  status: 'completed' | 'pending' | 'failed';
  reference?: string;
}

interface WalletData {
  balance: number;
  currency: string;
  totalRevenue: number;
  totalFees: number;
  totalWithdrawals: number;
  pendingPayouts: number;
  transactions: Transaction[];
  canWithdraw: boolean;
  withdrawalBlockReason?: string;
}

// Mock data for demonstration
const MOCK_WALLET: WalletData = {
  balance: 2450.00,
  currency: 'USD',
  totalRevenue: 3200.00,
  totalFees: 320.00,
  totalWithdrawals: 430.00,
  pendingPayouts: 150.00,
  canWithdraw: false,
  withdrawalBlockReason: 'Season 2 is still active. Withdrawals are available after season completion.',
  transactions: [
    {
      id: 'txn-1',
      type: 'sponsorship',
      description: 'Main Sponsor - TechCorp',
      amount: 1200.00,
      fee: 120.00,
      netAmount: 1080.00,
      date: new Date('2025-12-01'),
      status: 'completed',
      reference: 'SP-2025-001',
    },
    {
      id: 'txn-2',
      type: 'sponsorship',
      description: 'Secondary Sponsor - RaceFuel',
      amount: 400.00,
      fee: 40.00,
      netAmount: 360.00,
      date: new Date('2025-12-01'),
      status: 'completed',
      reference: 'SP-2025-002',
    },
    {
      id: 'txn-3',
      type: 'membership',
      description: 'Season Fee - 32 drivers',
      amount: 1600.00,
      fee: 160.00,
      netAmount: 1440.00,
      date: new Date('2025-11-15'),
      status: 'completed',
      reference: 'MF-2025-032',
    },
    {
      id: 'txn-4',
      type: 'withdrawal',
      description: 'Bank Transfer - Season 1 Payout',
      amount: -430.00,
      fee: 0,
      netAmount: -430.00,
      date: new Date('2025-10-30'),
      status: 'completed',
      reference: 'WD-2025-001',
    },
    {
      id: 'txn-5',
      type: 'prize',
      description: 'Championship Prize Pool (reserved)',
      amount: -150.00,
      fee: 0,
      netAmount: -150.00,
      date: new Date('2025-12-05'),
      status: 'pending',
      reference: 'PZ-2025-001',
    },
  ],
};

function TransactionRow({ transaction }: { transaction: Transaction }) {
  const isIncoming = transaction.amount > 0;
  
  const typeIcons = {
    sponsorship: DollarSign,
    membership: CreditCard,
    withdrawal: ArrowUpRight,
    prize: TrendingUp,
  };
  const TypeIcon = typeIcons[transaction.type];

  const statusConfig = {
    completed: { color: 'text-performance-green', bg: 'bg-performance-green/10', icon: CheckCircle },
    pending: { color: 'text-warning-amber', bg: 'bg-warning-amber/10', icon: Clock },
    failed: { color: 'text-racing-red', bg: 'bg-racing-red/10', icon: XCircle },
  };
  const status = statusConfig[transaction.status];
  const StatusIcon = status.icon;

  return (
    <div className="flex items-center justify-between p-4 border-b border-charcoal-outline last:border-b-0 hover:bg-iron-gray/30 transition-colors">
      <div className="flex items-center gap-4">
        <div className={`flex h-10 w-10 items-center justify-center rounded-lg ${isIncoming ? 'bg-performance-green/10' : 'bg-iron-gray/50'}`}>
          {isIncoming ? (
            <ArrowDownLeft className="w-5 h-5 text-performance-green" />
          ) : (
            <ArrowUpRight className="w-5 h-5 text-gray-400" />
          )}
        </div>
        <div>
          <div className="flex items-center gap-2">
            <span className="font-medium text-white">{transaction.description}</span>
            <span className={`px-2 py-0.5 rounded text-xs ${status.bg} ${status.color}`}>
              {transaction.status}
            </span>
          </div>
          <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
            <TypeIcon className="w-3 h-3" />
            <span className="capitalize">{transaction.type}</span>
            {transaction.reference && (
              <>
                <span>•</span>
                <span>{transaction.reference}</span>
              </>
            )}
            <span>•</span>
            <span>{transaction.date.toLocaleDateString()}</span>
          </div>
        </div>
      </div>
      <div className="text-right">
        <div className={`font-semibold ${isIncoming ? 'text-performance-green' : 'text-white'}`}>
          {isIncoming ? '+' : ''}{transaction.amount < 0 ? '-' : ''}${Math.abs(transaction.amount).toFixed(2)}
        </div>
        {transaction.fee > 0 && (
          <div className="text-xs text-gray-500">
            Fee: ${transaction.fee.toFixed(2)}
          </div>
        )}
      </div>
    </div>
  );
}

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

  const filteredTransactions = wallet.transactions.filter(
    t => filterType === 'all' || t.type === filterType
  );

  const handleWithdraw = async () => {
    if (!withdrawAmount || parseFloat(withdrawAmount) <= 0) return;
    
    setProcessing(true);
    try {
      const response = await fetch(`/api/wallets/${params.id}/withdraw`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          amount: parseFloat(withdrawAmount),
          currency: wallet.currency,
          seasonId: 'season-2', // Current active season
          destinationAccount: 'bank-account-***1234',
        }),
      });

      const result = await response.json();
      
      if (!response.ok) {
        alert(result.reason || result.error || 'Withdrawal failed');
        return;
      }

      alert(`Withdrawal of $${withdrawAmount} processed successfully!`);
      setShowWithdrawModal(false);
      setWithdrawAmount('');
      // Refresh wallet data
    } 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.balance.toFixed(2)}</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.totalRevenue.toFixed(2)}</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.totalFees.toFixed(2)}</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.pendingPayouts.toFixed(2)}</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.balance.toFixed(2)}</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.balance.toFixed(2)}
                  </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>
  );
}