'use client';

import React from 'react';
import { SponsorDashboardHeader } from '@/components/sponsors/SponsorDashboardHeader';
import { PricingTableShell, PricingTier } from '@/components/sponsors/PricingTableShell';
import { BillingSummaryPanel } from '@/components/sponsors/BillingSummaryPanel';
import { SponsorBrandingPreview } from '@/components/sponsors/SponsorBrandingPreview';
import { SponsorStatusChip } from '@/components/sponsors/SponsorStatusChip';
import {
  Trophy,
  Calendar,
  Eye,
  TrendingUp,
  Flag,
  BarChart3,
  Megaphone,
  CreditCard,
  FileText,
  type LucideIcon
} from 'lucide-react';
import { Card } from '@/ui/Card';
import { Button } from '@/ui/Button';
import { Heading } from '@/ui/Heading';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Link } from '@/ui/Link';
import { Container } from '@/ui/Container';
import { Grid } from '@/ui/Grid';
import { GridItem } from '@/ui/GridItem';
import { Surface } from '@/ui/Surface';
import { Icon } from '@/ui/Icon';
import { siteConfig } from '@/lib/siteConfig';
import { routes } from '@/lib/routing/RouteConfig';

interface SponsorLeagueDetailViewData {
  league: {
    id: string;
    name: string;
    game: string;
    season: string;
    description: string;
    tier: 'premium' | 'standard' | 'starter';
    rating: number;
    drivers: number;
    races: number;
    completedRaces: number;
    racesLeft: number;
    engagement: number;
    totalImpressions: number;
    formattedTotalImpressions: string;
    projectedTotal: number;
    formattedProjectedTotal: string;
    mainSponsorCpm: number;
    formattedMainSponsorCpm: string;
    avgViewsPerRace: number;
    formattedAvgViewsPerRace: string;
    nextRace?: {
      name: string;
      date: string;
    };
    sponsorSlots: {
      main: {
        available: boolean;
        price: number;
        benefits: string[];
      };
      secondary: {
        available: number;
        total: number;
        price: number;
        benefits: string[];
      };
    };
    tierConfig: {
      bgColor: string;
      color: string;
      border: string;
    };
  };
  drivers: Array<{
    id: string;
    position: number;
    name: string;
    team: string;
    country: string;
    races: number;
    impressions: number;
    formattedImpressions: string;
  }>;
  races: Array<{
    id: string;
    name: string;
    date: string;
    formattedDate: string;
    status: 'completed' | 'upcoming';
    views: number;
  }>;
}

export type SponsorLeagueDetailTab = 'overview' | 'drivers' | 'races' | 'sponsor';

interface SponsorLeagueDetailTemplateProps {
  viewData: SponsorLeagueDetailViewData;
  activeTab: SponsorLeagueDetailTab;
  setActiveTab: (tab: SponsorLeagueDetailTab) => void;
  selectedTier: 'main' | 'secondary';
  setSelectedTier: (tier: 'main' | 'secondary') => void;
}

export function SponsorLeagueDetailTemplate({ 
  viewData,
  activeTab,
  setActiveTab,
  selectedTier,
  setSelectedTier
}: SponsorLeagueDetailTemplateProps) {
  const league = viewData.league;

  const billingStats: Array<{
    label: string;
    value: string | number;
    icon: LucideIcon;
    variant: 'info' | 'success' | 'warning' | 'default';
  }> = [
    {
      label: 'Total Views',
      value: league.formattedTotalImpressions,
      icon: Eye,
      variant: 'info',
    },
    {
      label: 'Avg/Race',
      value: league.formattedAvgViewsPerRace,
      icon: TrendingUp,
      variant: 'success',
    },
    {
      label: 'Engagement',
      value: `${league.engagement}%`,
      icon: BarChart3,
      variant: 'warning',
    },
    {
      label: 'Races Left',
      value: league.racesLeft,
      icon: Calendar,
      variant: 'default',
    },
  ];

  const pricingTiers: PricingTier[] = [
    {
      id: 'main',
      name: 'Main Sponsor',
      price: league.sponsorSlots.main.price,
      period: 'Season',
      description: 'Exclusive primary branding across all league assets.',
      features: league.sponsorSlots.main.benefits,
      available: league.sponsorSlots.main.available,
      isPopular: true,
    },
    {
      id: 'secondary',
      name: 'Secondary Sponsor',
      price: league.sponsorSlots.secondary.price,
      period: 'Season',
      description: 'Supporting branding on cars and broadcast overlays.',
      features: league.sponsorSlots.secondary.benefits,
      available: league.sponsorSlots.secondary.available > 0,
    }
  ];

  return (
    <Container size="lg" py={8}>
      <Stack gap={8}>
        {/* Breadcrumb */}
        <Box>
          <Stack direction="row" align="center" gap={2}>
            <Link href={routes.sponsor.dashboard}>
              <Text size="sm" color="text-gray-400">Dashboard</Text>
            </Link>
            <Text size="sm" color="text-gray-500">/</Text>
            <Link href={routes.sponsor.leagues}>
              <Text size="sm" color="text-gray-400">Leagues</Text>
            </Link>
            <Text size="sm" color="text-gray-500">/</Text>
            <Text size="sm" color="text-white">{league.name}</Text>
          </Stack>
        </Box>

        {/* Header */}
        <SponsorDashboardHeader 
          sponsorName="Sponsor" 
          onRefresh={() => console.log('Refresh')} 
        />

        {/* Quick Stats */}
        <BillingSummaryPanel stats={billingStats} />

        {/* Tabs */}
        <Box borderBottom borderColor="border-neutral-800">
          <Stack direction="row" gap={6}>
            {(['overview', 'drivers', 'races', 'sponsor'] as const).map((tab) => (
              <Box
                key={tab}
                onClick={() => setActiveTab(tab)}
                pb={3}
                cursor="pointer"
                borderBottom={activeTab === tab}
                borderColor={activeTab === tab ? 'border-primary-blue' : 'border-transparent'}
                color={activeTab === tab ? 'text-primary-blue' : 'text-gray-400'}
              >
                <Text size="sm" weight="medium" uppercase>
                  {tab === 'sponsor' ? '🎯 Become a Sponsor' : tab}
                </Text>
              </Box>
            ))}
          </Stack>
        </Box>

        {/* Tab Content */}
        {activeTab === 'overview' && (
          <Grid cols={2} gap={6}>
            <Card>
              <Box mb={4}>
                <Heading level={2} icon={<Icon icon={Trophy} size={5} color="#3b82f6" />}>
                  League Information
                </Heading>
              </Box>
              <Stack gap={3}>
                <InfoRow label="Platform" value={league.game} />
                <InfoRow label="Season" value={league.season} />
                <InfoRow label="Duration" value="Oct 2025 - Feb 2026" />
                <InfoRow label="Drivers" value={league.drivers} />
                <InfoRow label="Races" value={league.races} last />
              </Stack>
            </Card>

            <Card>
              <Box mb={4}>
                <Heading level={2} icon={<Icon icon={TrendingUp} size={5} color="#10b981" />}>
                  Sponsorship Value
                </Heading>
              </Box>
              <Stack gap={3}>
                <InfoRow label="Total Season Views" value={league.formattedTotalImpressions} />
                <InfoRow label="Projected Total" value={league.formattedProjectedTotal} />
                <InfoRow label="Main Sponsor CPM" value={league.formattedMainSponsorCpm} color="text-performance-green" />
                <InfoRow label="Engagement Rate" value={`${league.engagement}%`} />
                <InfoRow label="League Rating" value={`${league.rating}/5.0`} last />
              </Stack>
            </Card>

            {league.nextRace && (
              <GridItem colSpan={2}>
                <Card>
                  <Box mb={4}>
                    <Heading level={2} icon={<Icon icon={Flag} size={5} color="#f59e0b" />}>
                      Next Race
                    </Heading>
                  </Box>
                  <Surface variant="muted" rounded="lg" border padding={4} bg="bg-warning-amber/5" borderColor="border-warning-amber/20">
                    <Stack direction="row" align="center" justify="between">
                      <Stack direction="row" align="center" gap={4}>
                        <Surface variant="muted" rounded="lg" padding={3} bg="bg-warning-amber/10">
                          <Icon icon={Flag} size={6} color="#f59e0b" />
                        </Surface>
                        <Box>
                          <Text size="lg" weight="semibold" color="text-white" block>{league.nextRace.name}</Text>
                          <Text size="sm" color="text-gray-400" block mt={1}>{league.nextRace.date}</Text>
                        </Box>
                      </Stack>
                      <Button variant="secondary">
                        View Schedule
                      </Button>
                    </Stack>
                  </Surface>
                </Card>
              </GridItem>
            )}
          </Grid>
        )}

        {activeTab === 'drivers' && (
          <Card p={0}>
            <Box p={4} borderBottom borderColor="border-neutral-800">
              <Heading level={2}>Championship Standings</Heading>
              <Text size="sm" color="text-gray-400" block mt={1}>Top drivers carrying sponsor branding</Text>
            </Box>
            <Stack gap={0}>
              {viewData.drivers.map((driver, index) => (
                <Box key={driver.id} p={4} borderBottom={index < viewData.drivers.length - 1} borderColor="border-neutral-800/50">
                  <Stack direction="row" align="center" justify="between">
                    <Stack direction="row" align="center" gap={4}>
                      <Surface variant="muted" rounded="full" padding={1} w="10" h="10" display="flex" alignItems="center" justifyContent="center" bg="bg-neutral-800">
                        <Text weight="bold" color="text-white">{driver.position}</Text>
                      </Surface>
                      <Box>
                        <Text weight="medium" color="text-white" block>{driver.name}</Text>
                        <Text size="sm" color="text-gray-500" block mt={1}>{driver.team} • {driver.country}</Text>
                      </Box>
                    </Stack>
                    <Stack direction="row" align="center" gap={8}>
                      <Box textAlign="right">
                        <Text weight="medium" color="text-white" block>{driver.races}</Text>
                        <Text size="xs" color="text-gray-500">races</Text>
                      </Box>
                      <Box textAlign="right">
                        <Text weight="semibold" color="text-white" block>{driver.formattedImpressions}</Text>
                        <Text size="xs" color="text-gray-500">views</Text>
                      </Box>
                    </Stack>
                  </Stack>
                </Box>
              ))}
            </Stack>
          </Card>
        )}

        {activeTab === 'races' && (
          <Card p={0}>
            <Box p={4} borderBottom borderColor="border-neutral-800">
              <Heading level={2}>Race Calendar</Heading>
              <Text size="sm" color="text-gray-400" block mt={1}>Season schedule with view statistics</Text>
            </Box>
            <Stack gap={0}>
              {viewData.races.map((race, index) => (
                <Box key={race.id} p={4} borderBottom={index < viewData.races.length - 1} borderColor="border-neutral-800/50">
                  <Stack direction="row" align="center" justify="between">
                    <Stack direction="row" align="center" gap={4}>
                      <Box w="3" h="3" rounded="full" bg={race.status === 'completed' ? 'bg-performance-green' : 'bg-warning-amber'} />
                      <Box>
                        <Text weight="medium" color="text-white" block>{race.name}</Text>
                        <Text size="sm" color="text-gray-500" block mt={1}>{race.formattedDate}</Text>
                      </Box>
                    </Stack>
                    <Box>
                      {race.status === 'completed' ? (
                        <Box textAlign="right">
                          <Text weight="semibold" color="text-white" block>{race.views.toLocaleString()}</Text>
                          <Text size="xs" color="text-gray-500">views</Text>
                        </Box>
                      ) : (
                        <SponsorStatusChip status="pending" label="Upcoming" />
                      )}
                    </Box>
                  </Stack>
                </Box>
              ))}
            </Stack>
          </Card>
        )}

        {activeTab === 'sponsor' && (
          <Grid cols={12} gap={6}>
            <GridItem colSpan={12} lgSpan={8}>
              <PricingTableShell 
                title="Sponsorship Tiers"
                tiers={pricingTiers}
                selectedId={selectedTier}
                onSelect={(id) => setSelectedTier(id as 'main' | 'secondary')}
              />
            </GridItem>
            
            <GridItem colSpan={12} lgSpan={4}>
              <Stack gap={6}>
                <SponsorBrandingPreview 
                  name="Your Brand" 
                />
                
                <Card>
                  <Box mb={4}>
                    <Heading level={2} icon={<Icon icon={CreditCard} size={5} color="#3b82f6" />}>
                      Sponsorship Summary
                    </Heading>
                  </Box>
                  
                  <Stack gap={3} mb={6}>
                    <InfoRow label="Selected Tier" value={`${selectedTier.charAt(0).toUpperCase() + selectedTier.slice(1)} Sponsor`} />
                    <InfoRow label="Season Price" value={`$${selectedTier === 'main' ? league.sponsorSlots.main.price : league.sponsorSlots.secondary.price}`} />
                    <InfoRow label={`Platform Fee (${siteConfig.fees.platformFeePercent}%)`} value={`$${((selectedTier === 'main' ? league.sponsorSlots.main.price : league.sponsorSlots.secondary.price) * siteConfig.fees.platformFeePercent / 100).toFixed(2)}`} />
                    <Box pt={4} borderTop borderColor="border-neutral-800">
                      <Stack direction="row" align="center" justify="between">
                        <Text weight="semibold" color="text-white">Total (excl. VAT)</Text>
                        <Text size="xl" weight="bold" color="text-white">
                          ${((selectedTier === 'main' ? league.sponsorSlots.main.price : league.sponsorSlots.secondary.price) * (1 + siteConfig.fees.platformFeePercent / 100)).toFixed(2)}
                        </Text>
                      </Stack>
                    </Box>
                  </Stack>

                  <Text size="xs" color="text-gray-500" block mb={4}>
                    {siteConfig.vat.notice}
                  </Text>

                  <Stack direction="row" gap={3}>
                    <Button variant="primary" fullWidth icon={<Icon icon={Megaphone} size={4} />}>
                      Request Sponsorship
                    </Button>
                    <Button variant="secondary" icon={<Icon icon={FileText} size={4} />}>
                      Download Info Pack
                    </Button>
                  </Stack>
                </Card>
              </Stack>
            </GridItem>
          </Grid>
        )}
      </Stack>
    </Container>
  );
}

function InfoRow({ label, value, color = 'text-white', last }: { label: string, value: string | number, color?: string, last?: boolean }) {
  return (
    <Box py={2} borderBottom={!last} borderColor="border-neutral-800/50">
      <Stack direction="row" align="center" justify="between">
        <Text color="text-gray-400">{label}</Text>
        <Text weight="medium" color={color}>{value}</Text>
      </Stack>
    </Box>
  );
}
