'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 { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Heading } from '@/ui/Heading';
import { Icon } from '@/ui/Icon';
import { Card } from '@/ui/Card';
import { Grid } from '@/ui/Grid';
 
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 (
    <Card rounded="xl" className="bg-iron-gray/50 border-charcoal-outline/40" p={4}>
      <Stack gap={3}>
        <Stack direction="row" align="center" gap={3}>
          <Stack h="9" w="9" align="center" justify="center" rounded="lg" bg={bgColor}>
            <Icon icon={icon} size={4} color={iconColor} />
          </Stack>
          <Heading level={3} fontSize="sm" weight="semibold" color="text-white">{title}</Heading>
        </Stack>
        {children}
      </Stack>
    </Card>
  );
}

// Info row component for consistent layout
function InfoRow({
  icon,
  label,
  value,
  valueClass = '',
}: {
  icon?: LucideIcon;
  label: string;
  value: React.ReactNode;
  valueClass?: string;
}) {
  return (
    <Stack direction="row" align="center" justify="between" py={2} borderBottom borderColor="border-charcoal-outline/20" 
      className="last:border-0"
    >
      <Stack direction="row" align="center" gap={2}>
        {icon && <Icon icon={icon} size={3.5} color="text-gray-500" />}
        <Text size="xs" color="text-gray-500">{label}</Text>
      </Stack>
      <Text size="sm" weight="medium" color="text-white" 
        className={valueClass}
      >
        {value}
      </Text>
    </Stack>
  );
}
 
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>
        <Stack 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 */}
          <Stack position="absolute" top={0} right={0} w="32" h="32" bg="bg-primary-blue/10" rounded="full" 
            className="blur-3xl" 
          >{null}</Stack>
          <Stack position="absolute" bottom="0" left="0" w="24" h="24" bg="bg-neon-aqua/5" rounded="full" 
            className="blur-2xl" 
          >{null}</Stack>
          
          <Stack position="relative" direction="row" align="start" gap={4}>
            <Stack h="14" w="14" align="center" justify="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" />
            </Stack>
            <Stack flexGrow={1} style={{ 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>
              <Stack direction="row" wrap align="center" gap={3}>
                {/* Ranked/Unranked Badge */}
                <Stack 
                  as="span" 
                  direction="row"
                  align="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 
                    style={{ fontSize: '10px' }} 
                    opacity={0.7}
                  >
                    • {visibilityDescription}
                  </Text>
                </Stack>
                <Stack as="span" direction="row" align="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>
                </Stack>
                <Stack as="span" direction="row" align="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>
                </Stack>
              </Stack>
            </Stack>
          </Stack>
        </Stack>
      </Stack>
  
      {/* Season Summary */}
      <Stack gap={3}>
        <Heading level={3} fontSize="sm" weight="semibold" color="text-gray-300">First season summary</Heading>
        <Stack direction="row" wrap align="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>
        </Stack>
        {/* Stats Grid */}
        <Grid cols={2} mdCols={4} gap={3}>
          {/* Capacity */}
          <Card rounded="xl" className="bg-iron-gray/50 border-charcoal-outline/40 text-center" p={4}>
            <Stack h="10" w="10" align="center" justify="center" rounded="lg" bg="bg-primary-blue/10" mx="auto" mb={2}>
              <Icon icon={Users} size={5} color="text-primary-blue" />
            </Stack>
            <Text size="2xl" weight="bold" color="text-white" block>{capacityValue}</Text>
            <Text size="xs" color="text-gray-500" block>{capacityLabel}</Text>
          </Card>
  
          {/* Rounds */}
          <Card rounded="xl" className="bg-iron-gray/50 border-charcoal-outline/40 text-center" p={4}>
            <Stack h="10" w="10" align="center" justify="center" rounded="lg" bg="bg-performance-green/10" mx="auto" mb={2}>
              <Icon icon={Flag} size={5} color="text-performance-green" />
            </Stack>
            <Text size="2xl" weight="bold" color="text-white" block>{timings.roundsPlanned ?? '—'}</Text>
            <Text size="xs" color="text-gray-500" block>rounds</Text>
          </Card>
  
          {/* Weekend Duration */}
          <Card rounded="xl" className="bg-iron-gray/50 border-charcoal-outline/40 text-center" p={4}>
            <Stack h="10" w="10" align="center" justify="center" rounded="lg" bg="bg-warning-amber/10" mx="auto" mb={2}>
              <Icon icon={Timer} size={5} color="text-warning-amber" />
            </Stack>
            <Text size="2xl" weight="bold" color="text-white" block>{totalWeekendMinutes > 0 ? `${totalWeekendMinutes}` : '—'}</Text>
            <Text size="xs" color="text-gray-500" block>min/weekend</Text>
          </Card>
  
          {/* Championships */}
          <Card rounded="xl" className="bg-iron-gray/50 border-charcoal-outline/40 text-center" p={4}>
            <Stack h="10" w="10" align="center" justify="center" rounded="lg" bg="bg-neon-aqua/10" mx="auto" mb={2}>
              <Icon icon={Award} size={5} color="text-neon-aqua" />
            </Stack>
            <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>
          </Card>
        </Grid>
      </Stack>
  
      {/* Detail Cards Grid */}
      <Grid cols={1} mdCols={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 */}
            <Stack direction="row" align="center" gap={3} p={3} rounded="lg" bg="bg-deep-graphite" border borderColor="border-charcoal-outline/30">
              <Text size="2xl">{getScoringEmoji()}</Text>
              <Stack flexGrow={1} style={{ 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>
              </Stack>
              {scoring.customScoringEnabled && (
                <Stack as="span" px={2} py={0.5} rounded="sm" bg="bg-primary-blue/20">
                  <Text 
                    style={{ fontSize: '10px' }} 
                    weight="medium" 
                    color="text-primary-blue"
                  >
                    Custom
                  </Text>
                </Stack>
              )}
            </Stack>
  
            {/* Drop Rule */}
            <Stack direction="row" align="center" gap={3} p={3} rounded="lg" bg="bg-deep-graphite" border borderColor="border-charcoal-outline/30">
              <Stack h="8" w="8" align="center" justify="center" rounded="lg" bg="bg-charcoal-outline/50">
                <Text size="base">{dropRuleInfo.emoji}</Text>
              </Stack>
              <Stack flexGrow={1} style={{ 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>
              </Stack>
            </Stack>
          </Stack>
        </ReviewCard>
      </Grid>
  
      {/* Championships Section */}
      <ReviewCard icon={Award} iconColor="text-neon-aqua" bgColor="bg-neon-aqua/10" title="Active Championships">
        <Stack direction="row" wrap gap={2}>
          {championships.enableDriverChampionship && (
            <Stack as="span" direction="row" align="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" />
            </Stack>
          )}
          {championships.enableTeamChampionship && (
            <Stack as="span" direction="row" align="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" />
            </Stack>
          )}
          {championships.enableNationsChampionship && (
            <Stack as="span" direction="row" align="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" />
            </Stack>
          )}
          {championships.enableTrophyChampionship && (
            <Stack as="span" direction="row" align="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" />
            </Stack>
          )}
          {![championships.enableDriverChampionship, championships.enableTeamChampionship, championships.enableNationsChampionship, championships.enableTrophyChampionship].some(Boolean) && (
            <Text size="sm" color="text-gray-500">No championships enabled</Text>
          )}
        </Stack>
      </ReviewCard>
  
      {/* Ready to launch message */}
      <Card rounded="xl" className="bg-performance-green/5 border-performance-green/20" p={4}>
        <Stack direction="row" align="center" gap={3}>
          <Stack h="10" w="10" align="center" justify="center" rounded="lg" bg="bg-performance-green/20">
            <Icon icon={Check} size={5} color="text-performance-green" />
          </Stack>
          <Stack>
            <Text size="sm" weight="medium" color="text-white" block>Ready to launch!</Text>
            <Text size="xs" color="text-gray-400" block>
              Click "Create League" to launch your racing series. You can modify all settings later.
            </Text>
          </Stack>
        </Stack>
      </Card>
    </Stack>
  );
}
