'use client';

import {
  Users,
  Calendar,
  Trophy,
  Award,
  Rocket,
  Gamepad2,
  User,
  UsersRound,
  Clock,
  Flag,
  Zap,
  Timer,
  Check,
  Globe,
  Medal,
  type LucideIcon,
} from 'lucide-react';
import type { LeagueConfigFormModel } from '@/lib/types/LeagueConfigFormModel';
import type { LeagueScoringPresetViewModel } from '@/lib/view-models/LeagueScoringPresetViewModel';
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';
 
interface LeagueReviewSummaryProps {
  form: LeagueConfigFormModel;
  presets: LeagueScoringPresetViewModel[];
}

// Individual review card component
function ReviewCard({
  icon,
  iconColor = 'text-primary-blue',
  bgColor = 'bg-primary-blue/10',
  title,
  children,
}: {
  icon: LucideIcon;
  iconColor?: string;
  bgColor?: string;
  title: string;
  children: React.ReactNode;
}) {
  return (
    <Box rounded="xl" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline/40" p={4}>
      <Stack gap={3}>
        <Box display="flex" alignItems="center" gap={3}>
          <Box display="flex" h="9" w="9" alignItems="center" justifyContent="center" rounded="lg" bg={bgColor}>
            <Icon icon={icon} size={4} color={iconColor} />
          </Box>
          <Heading level={3} fontSize="sm" weight="semibold" color="text-white">{title}</Heading>
        </Box>
        {children}
      </Stack>
    </Box>
  );
}

// Info row component for consistent layout
function InfoRow({
  icon,
  label,
  value,
  valueClass = '',
}: {
  icon?: LucideIcon;
  label: string;
  value: React.ReactNode;
  valueClass?: string;
}) {
  return (
    <Box display="flex" alignItems="center" justifyContent="between" py={2} borderBottom borderColor="border-charcoal-outline/20" 
      // eslint-disable-next-line gridpilot-rules/component-classification
      className="last:border-0"
    >
      <Box display="flex" alignItems="center" gap={2}>
        {icon && <Icon icon={icon} size={3.5} color="text-gray-500" />}
        <Text size="xs" color="text-gray-500">{label}</Text>
      </Box>
      <Text size="sm" weight="medium" color="text-white" 
        // eslint-disable-next-line gridpilot-rules/component-classification
        className={valueClass}
      >
        {value}
      </Text>
    </Box>
  );
}
 
export function LeagueReviewSummary({ form, presets }: LeagueReviewSummaryProps) {
  const { basics, structure, timings, scoring, championships, dropPolicy, stewarding } = form;
  const seasonName = (form as LeagueConfigFormModel & { seasonName?: string }).seasonName;
  
  const modeLabel =
    structure.mode === 'solo'
      ? 'Solo drivers'
      : 'Team-based';

  const capacityValue = (() => {
    if (structure.mode === 'solo') {
      return typeof structure.maxDrivers === 'number' ? structure.maxDrivers : '—';
    }
    return typeof structure.maxTeams === 'number' ? structure.maxTeams : '—';
  })();

  const capacityLabel = structure.mode === 'solo' ? 'drivers' : 'teams';
  
  const formatMinutes = (value: number | undefined) => {
    if (typeof value !== 'number' || value <= 0) return '—';
    return `${value} min`;
  };
  
  const getDropRuleInfo = () => {
    if (dropPolicy.strategy === 'none') {
      return { emoji: '✓', label: 'All count', description: 'Every race counts' };
    }
    if (dropPolicy.strategy === 'bestNResults') {
      return {
        emoji: '🏆',
        label: `Best ${dropPolicy.n ?? 'N'}`,
        description: `Only best ${dropPolicy.n ?? 'N'} results count`,
      };
    }
    if (dropPolicy.strategy === 'dropWorstN') {
      return {
        emoji: '🗑️',
        label: `Drop ${dropPolicy.n ?? 'N'}`,
        description: `Worst ${dropPolicy.n ?? 'N'} dropped`,
      };
    }
    return { emoji: '✓', label: 'All count', description: 'Every race counts' };
  };
  const dropRuleInfo = getDropRuleInfo();

  const preset = presets.find((p) => p.id === scoring.patternId) ?? null;

  const seasonStartLabel =
    timings.seasonStartDate
      ? new Date(timings.seasonStartDate).toLocaleDateString(undefined, {
          month: 'short',
          day: 'numeric',
          year: 'numeric',
        })
      : null;

  const stewardingLabel = (() => {
    switch (stewarding.decisionMode) {
      case 'admin_only':
        return 'Admin-only decisions';
      case 'steward_vote':
        return 'Steward panel voting';
      default:
        return stewarding.decisionMode;
    }
  })();

  
  const getScoringEmoji = () => {
    if (!preset) return '🏁';
    const name = preset.name.toLowerCase();
    if (name.includes('sprint') || name.includes('double')) return '⚡';
    if (name.includes('endurance') || name.includes('long')) return '🏆';
    if (name.includes('club') || name.includes('casual')) return '🏅';
    return '🏁';
  };
  
  // Normalize visibility to new terminology
  const isRanked = basics.visibility === 'public'; // public = ranked, private/unlisted = unranked
  const visibilityLabel = isRanked ? 'Ranked' : 'Unranked';
  const visibilityDescription = isRanked
    ? 'Competitive • Affects ratings'
    : 'Casual • Friends only';
  
  // Calculate total weekend duration
  const totalWeekendMinutes = (timings.practiceMinutes ?? 0) +
    (timings.qualifyingMinutes ?? 0) +
    (timings.sprintRaceMinutes ?? 0) +
    (timings.mainRaceMinutes ?? 0);
    
  return (
    <Stack gap={6}>
      {/* League Summary */}
      <Stack gap={3}>
        <Heading level={3} fontSize="sm" weight="semibold" color="text-gray-300">League summary</Heading>
        <Box position="relative" rounded="2xl" bg="bg-gradient-to-br from-primary-blue/20 via-iron-gray to-iron-gray" border borderColor="border-primary-blue/30" p={6} overflow="hidden">
          {/* Background decoration */}
          <Box position="absolute" top="0" right="0" w="32" h="32" bg="bg-primary-blue/10" rounded="full" 
            // eslint-disable-next-line gridpilot-rules/component-classification
            className="blur-3xl" 
          />
          <Box position="absolute" bottom="0" left="0" w="24" h="24" bg="bg-neon-aqua/5" rounded="full" 
            // eslint-disable-next-line gridpilot-rules/component-classification
            className="blur-2xl" 
          />
          
          <Box position="relative" display="flex" alignItems="start" gap={4}>
            <Box display="flex" h="14" w="14" alignItems="center" justifyContent="center" rounded="2xl" bg="bg-primary-blue/20" border borderColor="border-primary-blue/30" flexShrink={0}>
              <Icon icon={Rocket} size={7} color="text-primary-blue" />
            </Box>
            <Box flexGrow={1} minWidth="0">
              <Heading level={2} fontSize="xl" weight="bold" color="text-white" mb={1} truncate>
                {basics.name || 'Your New League'}
              </Heading>
              <Text size="sm" color="text-gray-400" mb={3} block>
                {basics.description || 'Ready to launch your racing series!'}
              </Text>
              <Box display="flex" flexWrap="wrap" alignItems="center" gap={3}>
                {/* Ranked/Unranked Badge */}
                <Box 
                  as="span" 
                  display="inline-flex" 
                  alignItems="center" 
                  gap={1.5} 
                  rounded="full" 
                  px={3} 
                  py={1.5}
                  bg={isRanked ? 'bg-primary-blue/15' : 'bg-neon-aqua/15'}
                  color={isRanked ? 'text-primary-blue' : 'text-neon-aqua'}
                  border
                  borderColor={isRanked ? 'border-primary-blue/30' : 'border-neon-aqua/30'}
                >
                  <Icon icon={isRanked ? Trophy : Users} size={3} />
                  <Text weight="semibold" size="xs">{visibilityLabel}</Text>
                  <Text 
                    // eslint-disable-next-line gridpilot-rules/component-classification
                    style={{ fontSize: '10px' }} 
                    opacity={0.7}
                  >
                    • {visibilityDescription}
                  </Text>
                </Box>
                <Box as="span" display="inline-flex" alignItems="center" gap={1.5} rounded="full" bg="bg-charcoal-outline/50" px={3} py={1} color="text-gray-300">
                  <Icon icon={Gamepad2} size={3} />
                  <Text size="xs" weight="medium">iRacing</Text>
                </Box>
                <Box as="span" display="inline-flex" alignItems="center" gap={1.5} rounded="full" bg="bg-charcoal-outline/50" px={3} py={1} color="text-gray-300">
                  <Icon icon={structure.mode === 'solo' ? User : UsersRound} size={3} />
                  <Text size="xs" weight="medium">{modeLabel}</Text>
                </Box>
              </Box>
            </Box>
          </Box>
        </Box>
      </Stack>
  
      {/* Season Summary */}
      <Stack gap={3}>
        <Heading level={3} fontSize="sm" weight="semibold" color="text-gray-300">First season summary</Heading>
        <Box display="flex" flexWrap="wrap" alignItems="center" gap={2}>
          <Text size="xs" color="text-gray-400">{seasonName || 'First season of this league'}</Text>
          {seasonStartLabel && (
            <>
              <Text size="xs" color="text-gray-400">•</Text>
              <Text size="xs" color="text-gray-400">Starts {seasonStartLabel}</Text>
            </>
          )}
          {typeof timings.roundsPlanned === 'number' && (
            <>
              <Text size="xs" color="text-gray-400">•</Text>
              <Text size="xs" color="text-gray-400">{timings.roundsPlanned} rounds planned</Text>
            </>
          )}
          <Text size="xs" color="text-gray-400">•</Text>
          <Text size="xs" color="text-gray-400">Stewarding: {stewardingLabel}</Text>
        </Box>
        {/* Stats Grid */}
        <Box display="grid" gridCols={{ base: 2, md: 4 }} gap={3}>
          {/* Capacity */}
          <Box rounded="xl" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline/40" p={4} textAlign="center">
            <Box display="flex" h="10" w="10" alignItems="center" justifyContent="center" rounded="lg" bg="bg-primary-blue/10" mx="auto" mb={2}>
              <Icon icon={Users} size={5} color="text-primary-blue" />
            </Box>
            <Text size="2xl" weight="bold" color="text-white" block>{capacityValue}</Text>
            <Text size="xs" color="text-gray-500" block>{capacityLabel}</Text>
          </Box>
  
          {/* Rounds */}
          <Box rounded="xl" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline/40" p={4} textAlign="center">
            <Box display="flex" h="10" w="10" alignItems="center" justifyContent="center" rounded="lg" bg="bg-performance-green/10" mx="auto" mb={2}>
              <Icon icon={Flag} size={5} color="text-performance-green" />
            </Box>
            <Text size="2xl" weight="bold" color="text-white" block>{timings.roundsPlanned ?? '—'}</Text>
            <Text size="xs" color="text-gray-500" block>rounds</Text>
          </Box>
  
          {/* Weekend Duration */}
          <Box rounded="xl" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline/40" p={4} textAlign="center">
            <Box display="flex" h="10" w="10" alignItems="center" justifyContent="center" rounded="lg" bg="bg-warning-amber/10" mx="auto" mb={2}>
              <Icon icon={Timer} size={5} color="text-warning-amber" />
            </Box>
            <Text size="2xl" weight="bold" color="text-white" block>{totalWeekendMinutes > 0 ? `${totalWeekendMinutes}` : '—'}</Text>
            <Text size="xs" color="text-gray-500" block>min/weekend</Text>
          </Box>
  
          {/* Championships */}
          <Box rounded="xl" bg="bg-iron-gray/50" border borderColor="border-charcoal-outline/40" p={4} textAlign="center">
            <Box display="flex" h="10" w="10" alignItems="center" justifyContent="center" rounded="lg" bg="bg-neon-aqua/10" mx="auto" mb={2}>
              <Icon icon={Award} size={5} color="text-neon-aqua" />
            </Box>
            <Text size="2xl" weight="bold" color="text-white" block>
              {[championships.enableDriverChampionship, championships.enableTeamChampionship, championships.enableNationsChampionship, championships.enableTrophyChampionship].filter(Boolean).length}
            </Text>
            <Text size="xs" color="text-gray-500" block>championships</Text>
          </Box>
        </Box>
      </Stack>
  
      {/* Detail Cards Grid */}
      <Box display="grid" gridCols={{ base: 1, md: 2 }} gap={4}>
        {/* Schedule Card */}
        <ReviewCard icon={Calendar} title="Race Weekend">
          <Stack gap={1}>
            {timings.practiceMinutes && timings.practiceMinutes > 0 && (
              <InfoRow icon={Clock} label="Practice" value={formatMinutes(timings.practiceMinutes)} />
            )}
            <InfoRow icon={Clock} label="Qualifying" value={formatMinutes(timings.qualifyingMinutes)} />
            {timings.sprintRaceMinutes && timings.sprintRaceMinutes > 0 && (
              <InfoRow icon={Zap} label="Sprint Race" value={formatMinutes(timings.sprintRaceMinutes)} />
            )}
            <InfoRow icon={Flag} label="Main Race" value={formatMinutes(timings.mainRaceMinutes)} />
          </Stack>
        </ReviewCard>
  
        {/* Scoring Card */}
        <ReviewCard icon={Trophy} iconColor="text-warning-amber" bgColor="bg-warning-amber/10" title="Scoring System">
          <Stack gap={3}>
            {/* Scoring Preset */}
            <Box display="flex" alignItems="center" gap={3} p={3} rounded="lg" bg="bg-deep-graphite" border borderColor="border-charcoal-outline/30">
              <Text size="2xl">{getScoringEmoji()}</Text>
              <Box flexGrow={1} minWidth="0">
                <Text size="sm" weight="medium" color="text-white" block>{preset?.name ?? 'Custom'}</Text>
                <Text size="xs" color="text-gray-500" block>{preset?.sessionSummary ?? 'Custom scoring enabled'}</Text>
              </Box>
              {scoring.customScoringEnabled && (
                <Box as="span" px={2} py={0.5} rounded="sm" bg="bg-primary-blue/20">
                  <Text 
                    // eslint-disable-next-line gridpilot-rules/component-classification
                    style={{ fontSize: '10px' }} 
                    weight="medium" 
                    color="text-primary-blue"
                  >
                    Custom
                  </Text>
                </Box>
              )}
            </Box>
  
            {/* Drop Rule */}
            <Box display="flex" alignItems="center" gap={3} p={3} rounded="lg" bg="bg-deep-graphite" border borderColor="border-charcoal-outline/30">
              <Box display="flex" h="8" w="8" alignItems="center" justifyContent="center" rounded="lg" bg="bg-charcoal-outline/50">
                <Text size="base">{dropRuleInfo.emoji}</Text>
              </Box>
              <Box flexGrow={1} minWidth="0">
                <Text size="sm" weight="medium" color="text-white" block>{dropRuleInfo.label}</Text>
                <Text size="xs" color="text-gray-500" block>{dropRuleInfo.description}</Text>
              </Box>
            </Box>
          </Stack>
        </ReviewCard>
      </Box>
  
      {/* Championships Section */}
      <ReviewCard icon={Award} iconColor="text-neon-aqua" bgColor="bg-neon-aqua/10" title="Active Championships">
        <Box display="flex" flexWrap="wrap" gap={2}>
          {championships.enableDriverChampionship && (
            <Box as="span" display="inline-flex" alignItems="center" gap={1.5} rounded="lg" bg="bg-primary-blue/10" border borderColor="border-primary-blue/20" px={3} py={2}>
              <Icon icon={Trophy} size={3.5} color="text-primary-blue" />
              <Text size="xs" weight="medium" color="text-primary-blue">Driver Championship</Text>
              <Icon icon={Check} size={3} color="text-performance-green" />
            </Box>
          )}
          {championships.enableTeamChampionship && (
            <Box as="span" display="inline-flex" alignItems="center" gap={1.5} rounded="lg" bg="bg-primary-blue/10" border borderColor="border-primary-blue/20" px={3} py={2}>
              <Icon icon={Award} size={3.5} color="text-primary-blue" />
              <Text size="xs" weight="medium" color="text-primary-blue">Team Championship</Text>
              <Icon icon={Check} size={3} color="text-performance-green" />
            </Box>
          )}
          {championships.enableNationsChampionship && (
            <Box as="span" display="inline-flex" alignItems="center" gap={1.5} rounded="lg" bg="bg-primary-blue/10" border borderColor="border-primary-blue/20" px={3} py={2}>
              <Icon icon={Globe} size={3.5} color="text-primary-blue" />
              <Text size="xs" weight="medium" color="text-primary-blue">Nations Cup</Text>
              <Icon icon={Check} size={3} color="text-performance-green" />
            </Box>
          )}
          {championships.enableTrophyChampionship && (
            <Box as="span" display="inline-flex" alignItems="center" gap={1.5} rounded="lg" bg="bg-primary-blue/10" border borderColor="border-primary-blue/20" px={3} py={2}>
              <Icon icon={Medal} size={3.5} color="text-primary-blue" />
              <Text size="xs" weight="medium" color="text-primary-blue">Trophy Championship</Text>
              <Icon icon={Check} size={3} color="text-performance-green" />
            </Box>
          )}
          {![championships.enableDriverChampionship, championships.enableTeamChampionship, championships.enableNationsChampionship, championships.enableTrophyChampionship].some(Boolean) && (
            <Text size="sm" color="text-gray-500">No championships enabled</Text>
          )}
        </Box>
      </ReviewCard>
  
      {/* Ready to launch message */}
      <Box rounded="xl" bg="bg-performance-green/5" border borderColor="border-performance-green/20" p={4}>
        <Box display="flex" alignItems="center" gap={3}>
          <Box display="flex" h="10" w="10" alignItems="center" justifyContent="center" rounded="lg" bg="bg-performance-green/20">
            <Icon icon={Check} size={5} color="text-performance-green" />
          </Box>
          <Box>
            <Text size="sm" weight="medium" color="text-white" block>Ready to launch!</Text>
            <Text size="xs" color="text-gray-400" block>
              Click &quot;Create League&quot; to launch your racing series. You can modify all settings later.
            </Text>
          </Box>
        </Box>
      </Box>
    </Stack>
  );
}