'use client';

import { RulebookTabs, type RulebookSection } from '@/components/leagues/RulebookTabs';
import { PointsTable } from '@/components/races/PointsTable';
import type { LeagueRulebookViewData } from '@/lib/view-data/LeagueRulebookViewData';
import { Box } from '@/ui/Box';
import { Heading } from '@/ui/Heading';
import { Icon } from '@/ui/Icon';
import { Grid } from '@/ui/Grid';
import { Stack } from '@/ui/Stack';
import { Surface } from '@/ui/Surface';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/ui/Table';
import { Text } from '@/ui/Text';
import { AlertTriangle, Book, Clock, Info, Scale, Shield, type LucideIcon } from 'lucide-react';

interface LeagueRulebookTemplateProps {
  viewData: LeagueRulebookViewData;
  activeSection: RulebookSection;
  onSectionChange: (section: RulebookSection) => void;
  loading?: boolean;
}

export function LeagueRulebookTemplate({
  viewData,
  activeSection,
  onSectionChange,
  loading = false,
}: LeagueRulebookTemplateProps) {
  if (loading) {
    return (
      <Surface variant="dark" border rounded="lg" padding={12} center>
        <Text color="text-gray-400">Loading rulebook...</Text>
      </Surface>
    );
  }

  if (!viewData || !viewData.scoringConfig) {
    return (
      <Surface variant="dark" border rounded="lg" padding={12} center>
        <Stack align="center" gap={3}>
          <Icon icon={AlertTriangle} size={8} color="text-warning-amber" />
          <Text color="text-gray-400">Unable to load rulebook</Text>
        </Stack>
      </Surface>
    );
  }

  const { scoringConfig } = viewData;
  const primaryChampionship = scoringConfig.championships.find(c => c.type === 'driver') ?? scoringConfig.championships[0];
  const positionPoints = viewData.positionPoints;

  return (
    <Stack gap={6}>
      {/* Navigation Tabs */}
      <RulebookTabs activeSection={activeSection} onSectionChange={onSectionChange} />

      {/* Content Sections */}
      {activeSection === 'scoring' && (
        <Stack gap={6}>
          {/* Quick Stats */}
          <Grid cols={1} mdCols={2} lgCols={4} gap={4}>
            <StatItem icon={Info} label="Platform" value={scoringConfig.gameName} color="text-primary-blue" />
            <StatItem icon={Book} label="Championships" value={scoringConfig.championships.length} color="text-neon-aqua" />
            <StatItem icon={Clock} label="Sessions" value={primaryChampionship?.sessionTypes.join(', ') || 'Main'} color="text-performance-green" />
            <StatItem icon={Shield} label="Drop Policy" value={scoringConfig.dropPolicySummary.includes('All') ? 'None' : 'Active'} color="text-warning-amber" />
          </Grid>

          {/* Weekend Structure */}
          <Surface variant="dark" border rounded="lg" padding={6}>
            <Stack gap={4}>
              <Stack direction="row" align="center" gap={2}>
                <Icon icon={Clock} size={5} color="text-primary-blue" />
                <Heading level={5} color="text-primary-blue">WEEKEND STRUCTURE</Heading>
              </Stack>
              <Grid cols={2} mdCols={4} gap={4}>
                <TimingItem label="PRACTICE" value="20 min" />
                <TimingItem label="QUALIFYING" value="30 min" />
                <TimingItem label="SPRINT" value="—" />
                <TimingItem label="MAIN RACE" value="40 min" />
              </Grid>
            </Stack>
          </Surface>

          {/* Points Table */}
          <PointsTable points={positionPoints} />

          {/* Bonus Points */}
          {primaryChampionship?.bonusSummary && primaryChampionship.bonusSummary.length > 0 && (
            <Surface variant="dark" border rounded="lg" padding={6}>
              <Stack gap={4}>
                <Heading level={5} color="text-performance-green">BONUS POINTS</Heading>
                <Stack gap={2}>
                  {primaryChampionship.bonusSummary.map((bonus, idx) => (
                    <Box key={idx} p={3} rounded="md" bg="bg-performance-green/5" border borderColor="border-performance-green/10">
                      <Stack direction="row" align="center" gap={3}>
                        <Box center w={6} h={6} rounded="full" bg="bg-performance-green/20">
                          <Text color="text-performance-green" weight="bold" size="xs">+</Text>
                        </Box>
                        <Text size="sm" color="text-gray-300">{bonus}</Text>
                      </Stack>
                    </Box>
                  ))}
                </Stack>
              </Stack>
            </Surface>
          )}
        </Stack>
      )}

      {activeSection === 'conduct' && (
        <Surface variant="dark" border rounded="lg" padding={6}>
          <Stack gap={6}>
            <Stack direction="row" align="center" gap={2}>
              <Icon icon={Shield} size={5} color="text-performance-green" />
              <Heading level={5} color="text-performance-green">DRIVER CONDUCT</Heading>
            </Stack>
            <Stack gap={4}>
              <ConductItem number={1} title="Respect" text="All drivers must treat each other with respect. Abusive language, harassment, or unsportsmanlike behavior will not be tolerated." />
              <ConductItem number={2} title="Clean Racing" text="Intentional wrecking, blocking, or dangerous driving is prohibited. Leave space for other drivers and race cleanly." />
              <ConductItem number={3} title="Track Limits" text="Drivers must stay within track limits. Gaining a lasting advantage by exceeding track limits may result in penalties." />
              <ConductItem number={4} title="Blue Flags" text="Lapped cars must yield to faster traffic within a reasonable time. Failure to do so may result in penalties." />
            </Stack>
          </Stack>
        </Surface>
      )}

      {activeSection === 'protests' && (
        <Surface variant="dark" border rounded="lg" padding={6}>
          <Stack gap={6}>
            <Stack direction="row" align="center" gap={2}>
              <Icon icon={Scale} size={5} color="text-warning-amber" />
              <Heading level={5} color="text-warning-amber">PROTEST PROCESS</Heading>
            </Stack>
            <Stack gap={4}>
              <ConductItem number={1} title="Filing a Protest" text="Protests can be filed within 48 hours of the race conclusion. Include the lap number, drivers involved, and a clear description of the incident." />
              <ConductItem number={2} title="Evidence" text="Video evidence is highly recommended but not required. Stewards will review available replay data." />
              <ConductItem number={3} title="Review Process" text="League stewards will review protests and make decisions within 72 hours. Decisions are final unless new evidence is presented." />
            </Stack>
          </Stack>
        </Surface>
      )}

      {activeSection === 'penalties' && (
        <Surface variant="dark" border rounded="lg" padding={6}>
          <Stack gap={6}>
            <Stack direction="row" align="center" gap={2}>
              <Icon icon={AlertTriangle} size={5} color="text-error-red" />
              <Heading level={5} color="text-error-red">PENALTY GUIDELINES</Heading>
            </Stack>
            <Table>
              <TableHead>
                <TableRow>
                  <TableHeader>Infraction</TableHeader>
                  <TableHeader>Typical Penalty</TableHeader>
                </TableRow>
              </TableHead>
              <TableBody>
                <PenaltyRow infraction="Causing avoidable contact" penalty="5-10 second time penalty" />
                <PenaltyRow infraction="Unsafe rejoin" penalty="5 second time penalty" />
                <PenaltyRow infraction="Blocking" penalty="Warning or 3 second penalty" />
                <PenaltyRow infraction="Intentional wrecking" penalty="Disqualification" isSevere />
              </TableBody>
            </Table>
          </Stack>
        </Surface>
      )}
    </Stack>
  );
}

function StatItem({ icon, label, value, color }: { icon: LucideIcon, label: string, value: string | number, color: string }) {
  return (
    <Surface variant="dark" border rounded="lg" padding={4}>
      <Stack direction="row" align="center" gap={3}>
        <Box center w={10} h={10} rounded="lg" bg="bg-white/5">
          <Icon icon={icon} size={5} color={color} />
        </Box>
        <Box>
          <Text size="xs" color="text-gray-500" weight="bold" letterSpacing="widest" display="block" mb={0.5}>{label.toUpperCase()}</Text>
          <Text weight="bold" color="text-white">{value}</Text>
        </Box>
      </Stack>
    </Surface>
  );
}

function TimingItem({ label, value }: { label: string, value: string }) {
  return (
    <Box p={3} rounded="md" bg="bg-white/5" border borderColor="border-white/10">
      <Text size="xs" color="text-gray-500" weight="bold" letterSpacing="widest" display="block" mb={1}>{label}</Text>
      <Text weight="bold" color="text-white">{value}</Text>
    </Box>
  );
}

function ConductItem({ number, title, text }: { number: number, title: string, text: string }) {
  return (
    <Box py={4} borderBottom borderColor="border-charcoal-outline">
      <Text weight="bold" color="text-white" display="block" mb={1}>{number}. {title}</Text>
      <Text size="sm" color="text-gray-400" lineHeight="relaxed">{text}</Text>
    </Box>
  );
}

function PenaltyRow({ infraction, penalty, isSevere }: { infraction: string, penalty: string, isSevere?: boolean }) {
  return (
    <TableRow>
      <TableCell>
        <Text size="sm" color="text-gray-300">{infraction}</Text>
      </TableCell>
      <TableCell>
        <Text size="sm" weight="bold" color={isSevere ? 'text-error-red' : 'text-warning-amber'}>{penalty}</Text>
      </TableCell>
    </TableRow>
  );
}
