'use client';

import { useState } from 'react';
import { Button } from '@/ui/Button';
import { Input } from '@/ui/Input';
import { Box } from '@/ui/Box';
import { Text } from '@/ui/Text';
import { Stack } from '@/ui/Stack';
import { Heading } from '@/ui/Heading';
import { Icon } from '@/ui/Icon';
import { DollarSign, Calendar, User, TrendingUp } from 'lucide-react';

type FeeType = 'season' | 'monthly' | 'per_race';

interface MembershipFeeConfig {
  type: FeeType;
  amount: number;
  enabled: boolean;
}

interface LeagueMembershipFeesSectionProps {
  leagueId: string;
  seasonId?: string;
  readOnly?: boolean;
}

export function LeagueMembershipFeesSection({ 
  readOnly = false 
}: LeagueMembershipFeesSectionProps) {
  const [feeConfig, setFeeConfig] = useState<MembershipFeeConfig>({
    type: 'season',
    amount: 0,
    enabled: false,
  });
  const [tempAmount, setTempAmount] = useState<string>('0');
  const [editing, setEditing] = useState(false);

  const handleEnableFees = () => {
    setFeeConfig({ ...feeConfig, enabled: true });
    setEditing(true);
    setTempAmount(feeConfig.amount.toString());
  };

  const handleSave = () => {
    const amount = parseFloat(tempAmount);
    if (!isNaN(amount) && amount > 0) {
      setFeeConfig({ ...feeConfig, amount });
    }
    setEditing(false);
  };

  const handleCancel = () => {
    setEditing(false);
    setTempAmount(feeConfig.amount.toString());
  };

  const handleTypeChange = (type: FeeType) => {
    setFeeConfig({ ...feeConfig, type });
  };

  const platformFee = feeConfig.amount * 0.10;
  const netAmount = feeConfig.amount - platformFee;

  const typeLabels: Record<FeeType, string> = {
    season: 'Season Fee',
    monthly: 'Monthly Subscription',
    per_race: 'Per-Race Fee',
  };

  const typeDescriptions: Record<FeeType, string> = {
    season: 'Single payment for entire season',
    monthly: 'Recurring monthly payment',
    per_race: 'Payment required per race entry',
  };

  return (
    <Stack gap={6}>
      {/* Header */}
      <Box display="flex" alignItems="center" justifyContent="between">
        <Box>
          <Heading level={3} fontSize="lg" weight="semibold" color="text-white">Membership Fees</Heading>
          <Text size="sm" color="text-gray-400" mt={1} block>
            Charge drivers for league participation
          </Text>
        </Box>
        {!feeConfig.enabled && !readOnly && (
          <Button
            variant="primary"
            onClick={handleEnableFees}
          >
            Enable Fees
          </Button>
        )}
      </Box>

      {!feeConfig.enabled ? (
        <Box textAlign="center" py={12} rounded="lg" border borderColor="border-charcoal-outline" bg="bg-iron-gray/30">
          <Box w="16" h="16" mx="auto" mb={4} rounded="full" bg="bg-iron-gray/50" display="flex" alignItems="center" justifyContent="center">
            <Icon icon={DollarSign} size={8} color="text-gray-500" />
          </Box>
          <Heading level={4} fontSize="lg" weight="medium" color="text-white" mb={2}>No Membership Fees</Heading>
          <Text size="sm" color="text-gray-400" maxWidth="md" mx="auto" block>
            This league is free to join. Enable membership fees to charge drivers for participation.
          </Text>
        </Box>
      ) : (
        <>
          {/* Fee Type Selection */}
          <Stack gap={3}>
            <Text as="label" size="sm" weight="medium" color="text-gray-300" block>
              Fee Type
            </Text>
            <Box display="grid" gridCols={3} gap={3}>
              {(['season', 'monthly', 'per_race'] as FeeType[]).map((type) => {
                const FeeIcon = type === 'season' ? Calendar : type === 'monthly' ? TrendingUp : User;
                const isSelected = feeConfig.type === type;
                
                return (
                  <Box
                    key={type}
                    as="button"
                    type="button"
                    onClick={() => handleTypeChange(type)}
                    disabled={readOnly}
                    p={4}
                    rounded="lg"
                    border
                    transition
                    borderColor={isSelected ? 'border-primary-blue' : 'border-charcoal-outline'}
                    bg={isSelected ? 'bg-primary-blue/10' : 'bg-iron-gray/30'}
                    hoverBorderColor={!isSelected ? 'border-primary-blue/50' : undefined}
                  >
                    <Icon icon={FeeIcon} size={5} mx="auto" mb={2} color={isSelected ? 'text-primary-blue' : 'text-gray-400'} />
                    <Text size="sm" weight="medium" color="text-white" block mb={1}>
                      {typeLabels[type]}
                    </Text>
                    <Text size="xs" color="text-gray-500" block>
                      {typeDescriptions[type]}
                    </Text>
                  </Box>
                );
              })}
            </Box>
          </Stack>

          {/* Amount Configuration */}
          <Stack gap={3}>
            <Text as="label" size="sm" weight="medium" color="text-gray-300" block>
              Amount
            </Text>
            
            {editing ? (
              <Box display="flex" alignItems="center" gap={3}>
                <Box flexGrow={1}>
                  <Input
                    type="number"
                    value={tempAmount}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTempAmount(e.target.value)}
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                  />
                </Box>
                <Button
                  variant="primary"
                  onClick={handleSave}
                  px={4}
                >
                  Save
                </Button>
                <Button
                  variant="secondary"
                  onClick={handleCancel}
                  px={4}
                >
                  Cancel
                </Button>
              </Box>
            ) : (
              <Box display="flex" alignItems="center" justifyContent="between" p={4} rounded="lg" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline">
                <Box>
                  <Text size="2xl" weight="bold" color="text-white" block>
                    ${feeConfig.amount.toFixed(2)}
                  </Text>
                  <Text size="xs" color="text-gray-500" mt={1} block>
                    {typeLabels[feeConfig.type]}
                  </Text>
                </Box>
                {!readOnly && (
                  <Button
                    variant="secondary"
                    onClick={() => setEditing(true)}
                    px={4}
                  >
                    Edit Amount
                  </Button>
                )}
              </Box>
            )}
          </Stack>

          {/* Revenue Breakdown */}
          {feeConfig.amount > 0 && (
            <Box display="grid" gridCols={2} gap={4}>
              <Box rounded="lg" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline" p={4}>
                <Text size="xs" color="text-gray-400" block mb={1}>Platform Fee (10%)</Text>
                <Text size="lg" weight="bold" color="text-warning-amber" block>
                  -${platformFee.toFixed(2)}
                </Text>
              </Box>
              <Box rounded="lg" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline" p={4}>
                <Text size="xs" color="text-gray-400" block mb={1}>Net per Driver</Text>
                <Text size="lg" weight="bold" color="text-performance-green" block>
                  ${netAmount.toFixed(2)}
                </Text>
              </Box>
            </Box>
          )}

          {/* Disable Fees */}
          {!readOnly && (
            <Box pt={4} borderTop borderColor="border-charcoal-outline">
              <Button
                variant="danger"
                onClick={() => setFeeConfig({ type: 'season', amount: 0, enabled: false })}
              >
                Disable Membership Fees
              </Button>
            </Box>
          )}
        </>
      )}

      {/* Alpha Notice */}
      <Box rounded="lg" bg="bg-warning-amber/10" border borderColor="border-warning-amber/30" p={4}>
        <Text size="xs" color="text-gray-400" block>
          <Text weight="bold" color="text-warning-amber">Alpha Note:</Text> Membership fee collection is demonstration-only.
          In production, fees are collected via payment gateway and deposited to league wallet (minus platform fee).
        </Text>
      </Box>
    </Stack>
  );
}