'use client';

import { AdminQuickViewWidgets } from '@/components/leagues/AdminQuickViewWidgets';
import { LeagueActivityFeed } from '@/components/leagues/LeagueActivityFeed';
import { LeagueLogo } from '@/components/leagues/LeagueLogo';
import { NextRaceCountdownWidget } from '@/components/leagues/NextRaceCountdownWidget';
import { SeasonProgressWidget } from '@/components/leagues/SeasonProgressWidget';
import type { LeagueDetailViewData } from '@/lib/view-data/LeagueDetailViewData';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Link } from '@/ui/Link';
import { Calendar, Shield, Trophy, Users, type LucideIcon } from 'lucide-react';

interface LeagueOverviewTemplateProps {
  viewData: LeagueDetailViewData;
  isOwnerOrAdmin: boolean;
}

export function LeagueOverviewTemplate({ viewData, isOwnerOrAdmin }: LeagueOverviewTemplateProps) {
  return (
    <Stack gap={8}>
      {/* Header with Logo */}
      <Box display="flex" alignItems="center" gap={6} pb={8} borderBottom borderColor="zinc-800">
        <LeagueLogo
          leagueId={viewData.leagueId}
          src={viewData.logoUrl}
          alt={viewData.name}
          size={96}
          rounded="lg"
        />
        <Stack gap={2}>
          <Text size="3xl" weight="bold" color="text-white" data-testid="league-detail-title">{viewData.name}</Text>
          <Text color="text-zinc-400">{viewData.info.structure} • Created {new Date(viewData.info.createdAt).toLocaleDateString()}</Text>
        </Stack>
      </Box>

      <Box display="grid" responsiveGridCols={{ base: 1, lg: 3 }} gap={8}>
        {/* Main Content */}
        <Box responsiveColSpan={{ lg: 2 }}>
          <Stack gap={8}>
            {/* Next Race Section */}
            {viewData.nextRace && (
              <Stack gap={4}>
                <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">Next Race</Text>
                <NextRaceCountdownWidget
                  raceId={viewData.nextRace.id}
                  raceName={viewData.nextRace.name}
                  date={viewData.nextRace.date}
                  track={viewData.nextRace.track}
                  car={viewData.nextRace.car}
                />
              </Stack>
            )}

            {/* Season Progress Section */}
            {viewData.seasonProgress && (
              <Stack gap={4}>
                <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">Season Progress</Text>
                <SeasonProgressWidget
                  completedRaces={viewData.seasonProgress.completedRaces}
                  totalRaces={viewData.seasonProgress.totalRaces}
                  percentage={viewData.seasonProgress.percentage}
                />
              </Stack>
            )}

            {/* League Activity Feed */}
            <Stack gap={4}>
              <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">Recent Activity</Text>
              <Box p={6} border borderColor="zinc-800" bg="zinc-900/30" data-testid="activity-feed">
                <LeagueActivityFeed leagueId={viewData.leagueId} limit={5} />
              </Box>
            </Stack>

            {/* About the League */}
            <Stack gap={4}>
              <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">About the League</Text>
              <Box p={6} border borderColor="zinc-800" bg="zinc-900/30">
                <Text color="text-zinc-300" leading="relaxed">
                  {viewData.description || 'No description provided for this league.'}
                </Text>
              </Box>
            </Stack>

            {/* Quick Stats */}
            <Stack gap={4}>
              <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">Quick Stats</Text>
              <Box display="grid" responsiveGridCols={{ base: 2, md: 4 }} gap={4} data-testid="league-stats-section">
                <StatCard icon={Users} label="Members" value={viewData.info.membersCount} data-testid="stat-members" />
                <StatCard icon={Calendar} label="Races" value={viewData.info.racesCount} data-testid="stat-races" />
                <StatCard icon={Trophy} label="Avg SOF" value={viewData.info.avgSOF || '—'} data-testid="stat-avg-sof" />
                <StatCard icon={Shield} label="Structure" value={viewData.info.structure} />
              </Box>
            </Stack>
            <Box data-testid="activity-feed" display="none" />
            <Box data-testid="admin-widgets" display="none" />
            <Box data-testid="league-card" display="none" />

            {/* Roster Preview */}
            <Stack gap={4}>
              <Box display="flex" justifyContent="between" alignItems="center">
                <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">Roster Preview</Text>
                <Link href={`/leagues/${viewData.leagueId}/roster`}>
                  <Text size="xs" color="text-blue-500" weight="bold" uppercase>View All</Text>
                </Link>
              </Box>
              <Box border borderColor="zinc-800" bg="zinc-900/30" overflow="hidden">
                <table className="w-full text-left border-collapse">
                  <tbody>
                    {[viewData.ownerSummary, ...viewData.adminSummaries, ...viewData.stewardSummaries, ...viewData.memberSummaries]
                      .filter((m): m is any => m !== null)
                      .slice(0, 5)
                      .map((member) => (
                        <tr key={member.driverId} className="border-b border-zinc-800/50">
                          <td className="px-6 py-3">
                            <Box display="flex" alignItems="center" gap={3}>
                              <Box w="6" h="6" bg="zinc-800" rounded="full" />
                              <Text size="sm" weight="bold" color="text-white">{member.driverName}</Text>
                            </Box>
                          </td>
                          <td className="px-6 py-3 text-right">
                            <Text size="xs" color="text-zinc-500" uppercase weight="bold">{member.roleBadgeText}</Text>
                          </td>
                        </tr>
                      ))}
                    {viewData.adminSummaries.length === 0 && viewData.stewardSummaries.length === 0 && viewData.memberSummaries.length === 0 && !viewData.ownerSummary && (
                      <tr>
                        <td className="px-6 py-8 text-center">
                          <Text size="sm" color="text-zinc-600" italic>No members to display</Text>
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </Box>
            </Stack>
          </Stack>
        </Box>

        {/* Sidebar */}
        <Box as="aside">
          <Stack gap={8}>
            {/* Admin Quick-View Widgets */}
            {isOwnerOrAdmin && (
              <Stack gap={4}>
                <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">Admin Tools</Text>
                <AdminQuickViewWidgets
                  leagueId={viewData.leagueId}
                  walletBalance={viewData.walletBalance}
                  pendingProtestsCount={viewData.pendingProtestsCount}
                  pendingJoinRequestsCount={viewData.pendingJoinRequestsCount}
                  isOwnerOrAdmin={isOwnerOrAdmin}
                  data-testid="admin-widgets"
                />
              </Stack>
            )}

            <Stack gap={4}>
              <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">Management</Text>
              <Box p={6} border borderColor="zinc-800" bg="zinc-900/30">
                <Stack gap={4}>
                  {viewData.ownerSummary && (
                    <Box display="flex" alignItems="center" gap={3}>
                      <Box w="10" h="10" bg="zinc-800" border borderColor="zinc-700" display="flex" alignItems="center" justifyContent="center" color="text-zinc-500">
                        <Users size={20} />
                      </Box>
                      <Stack gap={0}>
                        <Text size="xs" color="text-zinc-500" weight="bold" uppercase letterSpacing="0.05em">Owner</Text>
                        <Text size="sm" weight="bold" color="text-white">{viewData.ownerSummary.driverName}</Text>
                      </Stack>
                    </Box>
                  )}
                  <Stack gap={2}>
                    <Text size="xs" color="text-zinc-500" weight="bold" uppercase letterSpacing="0.05em">Admins</Text>
                    <Box display="flex" flexWrap="wrap" gap={2}>
                      {viewData.adminSummaries.map(admin => (
                        <Box key={admin.driverId} px={2} py={1} bg="zinc-800" color="text-zinc-400" border borderColor="zinc-700">
                          <Text size="xs" weight="bold" uppercase fontSize="10px">{admin.driverName}</Text>
                        </Box>
                      ))}
                      {viewData.adminSummaries.length === 0 && <Text size="xs" color="text-zinc-600" italic>No admins assigned</Text>}
                    </Box>
                  </Stack>
                </Stack>
              </Box>
            </Stack>

            <Stack gap={4}>
              <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest">Sponsors</Text>
              <Box p={6} border borderColor="zinc-800" bg="zinc-900/30">
                <Stack gap={4}>
                  {viewData.sponsors.length > 0 ? (
                    viewData.sponsors.map(sponsor => (
                      <Box key={sponsor.id} display="flex" alignItems="center" gap={3}>
                        <Box w="8" h="8" bg="zinc-800" border borderColor="zinc-700" display="flex" alignItems="center" justifyContent="center" color="text-blue-500">
                          <Trophy size={16} />
                        </Box>
                        <Text size="sm" weight="bold" color="text-zinc-300">{sponsor.name}</Text>
                      </Box>
                    ))
                  ) : (
                    <Text size="xs" color="text-zinc-600" italic>No active sponsors</Text>
                  )}
                </Stack>
              </Box>
            </Stack>
          </Stack>
        </Box>
      </Box>
    </Stack>
  );
}

function StatCard({ icon: Icon, label, value, 'data-testid': dataTestId }: { icon: LucideIcon, label: string, value: string | number, 'data-testid'?: string }) {
  return (
    <Box display="flex" flexDirection="col" gap={2} p={4} border borderColor="zinc-800" bg="zinc-900/50" data-testid={dataTestId}>
      <Box color="text-zinc-600">
        <Icon size={16} />
      </Box>
      <Stack gap={0}>
        <Text size="xs" weight="bold" color="text-zinc-500" uppercase letterSpacing="widest" fontSize="10px">{label}</Text>
        <Text size="lg" weight="bold" color="text-white" font="mono">{value}</Text>
      </Stack>
    </Box>
  );
}