'use client';

import { Button } from '@/ui/Button';
import { Heading } from '@/ui/Heading';
import { Icon } from '@/ui/Icon';
import { Input } from '@/ui/Input';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Calendar, DollarSign, TrendingUp, User } from 'lucide-react';
import { useState } from '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 */}
      <Stack display="flex" alignItems="center" justifyContent="between">
        <Stack>
          <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>
        </Stack>
        {!feeConfig.enabled && !readOnly && (
          <Button
            variant="primary"
            onClick={handleEnableFees}
          >
            Enable Fees
          </Button>
        )}
      </Stack>

      {!feeConfig.enabled ? (
        <Stack textAlign="center" py={12} rounded="lg" border borderColor="border-charcoal-outline" bg="bg-iron-gray/30">
          <Stack 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" />
          </Stack>
          <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>
        </Stack>
      ) : (
        <>
          {/* Fee Type Selection */}
          <Stack gap={3}>
            <Text as="label" size="sm" weight="medium" color="text-gray-300" block>
              Fee Type
            </Text>
            <Stack 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 (
                  <Stack
                    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>
                  </Stack>
                );
              })}
            </Stack>
          </Stack>

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

          {/* Revenue Breakdown */}
          {feeConfig.amount > 0 && (
            <Stack display="grid" gridCols={2} gap={4}>
              <Stack 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>
              </Stack>
              <Stack 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>
              </Stack>
            </Stack>
          )}

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

      {/* Alpha Notice */}
      <Stack 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>
      </Stack>
    </Stack>
  );
}