'use client';

import React, { useState, useMemo } from 'react';
import { Card } from '@/ui/Card';
import { Button } from '@/ui/Button';
import { TransactionRow } from '@/components/leagues/TransactionRow';
import type { LeagueWalletViewData } from '@/lib/view-data/leagues/LeagueWalletViewData';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Heading } from '@/ui/Heading';
import { Container } from '@/ui/Container';
import { Grid } from '@/ui/Grid';
import { Icon as UIIcon } from '@/ui/Icon';
import {
  Wallet,
  DollarSign,
  ArrowUpRight,
  Clock,
  AlertTriangle,
  Download,
  TrendingUp
} from 'lucide-react';

interface WalletTemplateProps {
  viewData: LeagueWalletViewData;
  onWithdraw?: (amount: number) => void;
  onExport?: () => void;
  mutationLoading?: boolean;
}

export function LeagueWalletPageClient({ viewData, onWithdraw, onExport, mutationLoading = false }: WalletTemplateProps) {
  const [withdrawAmount, setWithdrawAmount] = useState('');
  const [showWithdrawModal, setShowWithdrawModal] = useState(false);
  const [filterType, setFilterType] = useState<'all' | 'sponsorship' | 'membership' | 'withdrawal' | 'prize'>('all');

  const filteredTransactions = useMemo(() => {
    if (filterType === 'all') return viewData.transactions;
    return viewData.transactions.filter(t => t.type === filterType);
  }, [viewData.transactions, filterType]);

  const handleWithdrawClick = () => {
    const amount = parseFloat(withdrawAmount);
    if (!amount || amount <= 0) return;
    
    if (onWithdraw) {
      onWithdraw(amount);
      setShowWithdrawModal(false);
      setWithdrawAmount('');
    }
  };

  const canWithdraw = viewData.balance > 0;
  const withdrawalBlockReason = !canWithdraw ? 'Balance is zero' : undefined;

  return (
    <Container size="lg" py={8}>
      {/* Header */}
      <Box display="flex" alignItems="center" justifyContent="between" mb={8}>
        <Box>
          <Heading level={1}>League Wallet</Heading>
          <Text color="text-gray-400">Manage your league&apos;s finances and payouts</Text>
        </Box>
        <Stack direction="row" align="center" gap={2}>
          <Button variant="secondary" onClick={onExport}>
            <Stack direction="row" align="center" gap={2}>
              <UIIcon icon={Download} size={4} />
              <Text>Export</Text>
            </Stack>
          </Button>
          <Button
            variant="primary"
            onClick={() => setShowWithdrawModal(true)}
            disabled={!canWithdraw || !onWithdraw}
          >
            <Stack direction="row" align="center" gap={2}>
              <UIIcon icon={ArrowUpRight} size={4} />
              <Text>Withdraw</Text>
            </Stack>
          </Button>
        </Stack>
      </Box>

      {/* Withdrawal Warning */}
      {!canWithdraw && withdrawalBlockReason && (
        <Box mb={6} p={4} rounded="lg" bg="bg-warning-amber/10" border borderColor="border-warning-amber/30">
          <Stack direction="row" align="start" gap={3}>
            <UIIcon icon={AlertTriangle} size={5} color="text-warning-amber" flexShrink={0} mt={0.5} />
            <Box>
              <Text weight="medium" color="text-warning-amber" block>Withdrawals Temporarily Unavailable</Text>
              <Text size="sm" color="text-gray-400" block mt={1}>{withdrawalBlockReason}</Text>
            </Box>
          </Stack>
        </Box>
      )}

      {/* Stats Grid */}
      <Grid cols={1} mdCols={2} lgCols={4} gap={4} mb={8}>
        <Card>
          <Box p={4}>
            <Stack direction="row" align="center" gap={3}>
              <Box display="flex" h={12} w={12} alignItems="center" justifyContent="center" rounded="xl" bg="bg-performance-green/10">
                <UIIcon icon={Wallet} size={6} color="text-performance-green" />
              </Box>
              <Box>
                <Text size="2xl" weight="bold" color="text-white" block>{viewData.formattedBalance}</Text>
                <Text size="sm" color="text-gray-400" block>Available Balance</Text>
              </Box>
            </Stack>
          </Box>
        </Card>

        <Card>
          <Box p={4}>
            <Stack direction="row" align="center" gap={3}>
              <Box display="flex" h={12} w={12} alignItems="center" justifyContent="center" rounded="xl" bg="bg-primary-blue/10">
                <UIIcon icon={TrendingUp} size={6} color="text-primary-blue" />
              </Box>
              <Box>
                <Text size="2xl" weight="bold" color="text-white" block>{viewData.formattedTotalRevenue}</Text>
                <Text size="sm" color="text-gray-400" block>Total Revenue</Text>
              </Box>
            </Stack>
          </Box>
        </Card>

        <Card>
          <Box p={4}>
            <Stack direction="row" align="center" gap={3}>
              <Box display="flex" h={12} w={12} alignItems="center" justifyContent="center" rounded="xl" bg="bg-warning-amber/10">
                <UIIcon icon={DollarSign} size={6} color="text-warning-amber" />
              </Box>
              <Box>
                <Text size="2xl" weight="bold" color="text-white" block>{viewData.formattedTotalFees}</Text>
                <Text size="sm" color="text-gray-400" block>Platform Fees (10%)</Text>
              </Box>
            </Stack>
          </Box>
        </Card>

        <Card>
          <Box p={4}>
            <Stack direction="row" align="center" gap={3}>
              <Box display="flex" h={12} w={12} alignItems="center" justifyContent="center" rounded="xl" bg="bg-purple-500/10">
                <UIIcon icon={Clock} size={6} color="text-purple-400" />
              </Box>
              <Box>
                <Text size="2xl" weight="bold" color="text-white" block>{viewData.formattedPendingPayouts}</Text>
                <Text size="sm" color="text-gray-400" block>Pending Payouts</Text>
              </Box>
            </Stack>
          </Box>
        </Card>
      </Grid>

      {/* Transactions */}
      <Card>
        <Box display="flex" alignItems="center" justifyContent="between" p={4} borderBottom borderColor="border-charcoal-outline">
          <Heading level={2}>Transaction History</Heading>
          <Box as="select"
            value={filterType}
            onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setFilterType(e.target.value as typeof filterType)}
            p={1.5}
            rounded="lg"
            border
            borderColor="border-charcoal-outline"
            bg="bg-iron-gray"
            color="text-white"
            fontSize="sm"
          >
            <Box as="option" value="all">All Transactions</Box>
            <Box as="option" value="sponsorship">Sponsorships</Box>
            <Box as="option" value="membership">Memberships</Box>
            <Box as="option" value="withdrawal">Withdrawals</Box>
            <Box as="option" value="prize">Prizes</Box>
          </Box>
        </Box>

        {filteredTransactions.length === 0 ? (
          <Box py={12} textAlign="center">
            <Box display="flex" justifyContent="center" mb={4}>
              <UIIcon icon={Wallet} size={12} color="text-gray-500" />
            </Box>
            <Heading level={3}>No Transactions</Heading>
            <Box mt={2}>
              <Text color="text-gray-400">
                {filterType === 'all' 
                  ? 'Revenue from sponsorships and fees will appear here.'
                  : `No ${filterType} transactions found.`}
              </Text>
            </Box>
          </Box>
        ) : (
          <Box>
            {filteredTransactions.map((transaction) => (
              <TransactionRow 
                key={transaction.id} 
                transaction={{
                  id: transaction.id,
                  type: transaction.type,
                  description: transaction.description,
                  formattedDate: transaction.formattedDate,
                  formattedAmount: transaction.formattedAmount,
                  typeColor: transaction.type === 'withdrawal' ? 'text-red-400' : 'text-performance-green',
                  status: transaction.status,
                  statusColor: transaction.status === 'completed' ? 'text-performance-green' : 'text-warning-amber',
                  amountColor: transaction.type === 'withdrawal' ? 'text-red-400' : 'text-performance-green',
                }} 
              />
            ))}
          </Box>
        )}
      </Card>

      {/* Revenue Breakdown */}
      <Grid cols={1} lgCols={2} gap={6} mt={6}>
        <Card>
          <Box p={4}>
            <Heading level={3} mb={4}>Revenue Breakdown</Heading>
            <Stack gap={3}>
              <Box display="flex" alignItems="center" justifyContent="between">
                <Stack direction="row" align="center" gap={2}>
                  <Box w={3} h={3} rounded="full" bg="bg-primary-blue" />
                  <Text color="text-gray-400">Sponsorships</Text>
                </Stack>
                <Text weight="medium" color="text-white">$1,600.00</Text>
              </Box>
              <Box display="flex" alignItems="center" justifyContent="between">
                <Stack direction="row" align="center" gap={2}>
                  <Box w={3} h={3} rounded="full" bg="bg-performance-green" />
                  <Text color="text-gray-400">Membership Fees</Text>
                </Stack>
                <Text weight="medium" color="text-white">$1,600.00</Text>
              </Box>
              <Box display="flex" alignItems="center" justifyContent="between" pt={2} borderTop borderColor="border-charcoal-outline">
                <Text weight="medium" color="text-gray-300">Total Gross Revenue</Text>
                <Text weight="bold" color="text-white">$3,200.00</Text>
              </Box>
              <Box display="flex" alignItems="center" justifyContent="between">
                <Text size="sm" color="text-warning-amber">Platform Fee (10%)</Text>
                <Text size="sm" color="text-warning-amber">-$320.00</Text>
              </Box>
              <Box display="flex" alignItems="center" justifyContent="between" pt={2} borderTop borderColor="border-charcoal-outline">
                <Text weight="medium" color="text-performance-green">Net Revenue</Text>
                <Text weight="bold" color="text-performance-green">$2,880.00</Text>
              </Box>
            </Stack>
          </Box>
        </Card>

        <Card>
          <Box p={4}>
            <Heading level={3} mb={4}>Payout Schedule</Heading>
            <Stack gap={3}>
              <Box p={3} rounded="lg" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline">
                <Box display="flex" alignItems="center" justifyContent="between" mb={1}>
                  <Text size="sm" weight="medium" color="text-white">Season 2 Prize Pool</Text>
                  <Text size="sm" weight="medium" color="text-warning-amber">Pending</Text>
                </Box>
                <Text size="xs" color="text-gray-500">
                  Distributed after season completion to top 3 drivers
                </Text>
              </Box>
              <Box p={3} rounded="lg" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline">
                <Box display="flex" alignItems="center" justifyContent="between" mb={1}>
                  <Text size="sm" weight="medium" color="text-white">Available for Withdrawal</Text>
                  <Text size="sm" weight="medium" color="text-performance-green">{viewData.formattedBalance}</Text>
                </Box>
                <Text size="xs" color="text-gray-500">
                  Available after Season 2 ends (estimated: Jan 15, 2026)
                </Text>
              </Box>
            </Stack>
          </Box>
        </Card>
      </Grid>

      {/* Withdraw Modal */}
      {showWithdrawModal && onWithdraw && (
        <Box position="fixed" inset="0" bg="bg-black/50" display="flex" alignItems="center" justifyContent="center" zIndex={50}>
          <Card>
            <Box p={6} w="full" maxWidth="28rem">
              <Heading level={2} mb={4}>Withdraw Funds</Heading>
              
              {!canWithdraw ? (
                <Box p={4} rounded="lg" bg="bg-warning-amber/10" border borderColor="border-warning-amber/30" mb={4}>
                  <Text size="sm" color="text-warning-amber">{withdrawalBlockReason}</Text>
                </Box>
              ) : (
                <Stack gap={4}>
                  <Box>
                    <Text as="label" size="sm" weight="medium" color="text-gray-300" block mb={2}>
                      Amount to Withdraw
                    </Text>
                    <Box position="relative">
                      <Box position="absolute" left={3} top="50%" transform="translateY(-50%)">
                        <Text color="text-gray-500">$</Text>
                      </Box>
                      <Box as="input"
                        type="number"
                        value={withdrawAmount}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setWithdrawAmount(e.target.value)}
                        max={viewData.balance}
                        w="full"
                        pl={8}
                        pr={4}
                        py={2}
                        rounded="lg"
                        border
                        borderColor="border-charcoal-outline"
                        bg="bg-iron-gray"
                        color="text-white"
                        placeholder="0.00"
                      />
                    </Box>
                    <Text size="xs" color="text-gray-500" block mt={1}>
                      Available: {viewData.formattedBalance}
                    </Text>
                  </Box>

                  <Box>
                    <Text as="label" size="sm" weight="medium" color="text-gray-300" block mb={2}>
                      Destination
                    </Text>
                    <Box as="select"
                      w="full"
                      px={3}
                      py={2}
                      rounded="lg"
                      border
                      borderColor="border-charcoal-outline"
                      bg="bg-iron-gray"
                      color="text-white"
                    >
                      <Box as="option">Bank Account ***1234</Box>
                    </Box>
                  </Box>
                </Stack>
              )}

              <Stack direction="row" gap={3} mt={6}>
                <Button
                  variant="secondary"
                  onClick={() => setShowWithdrawModal(false)}
                  fullWidth
                >
                  Cancel
                </Button>
                <Button
                  variant="primary"
                  onClick={handleWithdrawClick}
                  disabled={!canWithdraw || mutationLoading || !withdrawAmount}
                  fullWidth
                >
                  {mutationLoading ? 'Processing...' : 'Withdraw'}
                </Button>
              </Stack>
            </Box>
          </Card>
        </Box>
      )}

      {/* Alpha Notice */}
      <Box mt={6} rounded="lg" bg="bg-warning-amber/10" border borderColor="border-warning-amber/30" p={4}>
        <Text size="xs" color="text-gray-400">
          <Text weight="bold" color="text-warning-amber">Alpha Note:</Text> 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.
        </Text>
      </Box>
    </Container>
  );
}

