'use client';

import { SlotTemplates } from '@/components/sponsors/SlotTemplates';
import { SponsorInsightsCard } from '@/components/sponsors/SponsorInsightsCard';
import { useSponsorMode } from '@/hooks/sponsor/useSponsorMode';
import { Breadcrumbs } from '@/ui/Breadcrumbs';
import { Button } from '@/ui/Button';
import { Container } from '@/ui/Container';
import { Heading } from '@/ui/Heading';
import { HorizontalStatItem } from '@/ui/HorizontalStatItem';
import { Box } from '@/ui/primitives/Box';
import { Grid } from '@/ui/primitives/Grid';
import { GridItem } from '@/ui/primitives/GridItem';
import { Stack } from '@/ui/primitives/Stack';
import { Text } from '@/ui/Text';

import { TeamAdmin } from '@/components/teams/TeamAdmin';
import { TeamDetailsHeader } from '@/components/teams/TeamDetailsHeader';
import { TeamMembersTable } from '@/components/teams/TeamMembersTable';
import { TeamStandingsPanel } from '@/components/teams/TeamStandingsPanel';
import type { TeamDetailViewData } from '@/lib/view-data/TeamDetailViewData';

type Tab = 'overview' | 'roster' | 'standings' | 'admin';

export interface TeamDetailTemplateProps {
  viewData: TeamDetailViewData;
  activeTab: Tab;
  loading: boolean;
  
  // Event handlers
  onTabChange: (tab: Tab) => void;
  onUpdate: () => void;
  onRemoveMember: (driverId: string) => void;
  onGoBack: () => void;
}

export function TeamDetailTemplate({
  viewData,
  activeTab,
  loading,
  onTabChange,
  onUpdate,
  onRemoveMember,
  onGoBack,
}: TeamDetailTemplateProps) {
  const isSponsorMode = useSponsorMode();
  const team = viewData.team;

  if (loading) {
    return (
      <Box bg="base-black" minH="screen" display="flex" center>
        <Stack align="center" gap={4}>
          <Box w="12" h="12" border={4} borderColor="primary-accent" borderOpacity={0.2} borderTop borderTopColor="primary-accent" rounded="full" animate="spin" />
          <Text color="text-gray-500" font="mono" size="xs" uppercase letterSpacing="widest">Synchronizing Telemetry...</Text>
        </Stack>
      </Box>
    );
  }

  if (!team) {
    return (
      <Box bg="base-black" minH="screen">
        <Container size="md" py={24}>
          <Box border borderColor="outline-steel" bg="surface-charcoal" p={12} textAlign="center">
            <Heading level={1}>404: Team Disconnected</Heading>
            <Text color="text-gray-500" block mt={4} font="mono">
              The requested team entity is no longer broadcasting.
            </Text>
            <Box mt={8}>
              <Button variant="primary" onClick={onGoBack}>
                Return to Base
              </Button>
            </Box>
          </Box>
        </Container>
      </Box>
    );
  }

  return (
    <Box bg="base-black" minH="screen">
      <Container size="lg" py={8}>
        <Stack gap={8}>
          <Breadcrumbs
            items={[
              { label: 'Home', href: '/' },
              { label: 'Teams', href: '/teams' },
              { label: team.name }
            ]}
          />

          {isSponsorMode && (
            <SponsorInsightsCard
              entityType="team"
              entityId={team.id}
              entityName={team.name}
              tier="standard"
              metrics={viewData.teamMetrics}
              slots={SlotTemplates.team(true, true, 500, 250)}
              trustScore={90}
              monthlyActivity={85}
              onNavigate={(href) => window.location.href = href}
            />
          )}

          <TeamDetailsHeader
            teamId={team.id}
            name={team.name}
            tag={team.tag}
            description={team.description}
            memberCount={viewData.memberships.length}
            foundedDate={team.createdAt}
            isAdmin={viewData.isAdmin}
            onAdminClick={() => onTabChange('admin')}
          />

          {/* Tabs */}
          <Box borderBottom borderColor="outline-steel">
            <Stack direction="row" gap={8}>
              {viewData.tabs.map((tab) => (
                tab.visible && (
                  <Box
                    key={tab.id}
                    onClick={() => onTabChange(tab.id)}
                    pb={4}
                    cursor="pointer"
                    position="relative"
                  >
                    <Text 
                      weight="bold" 
                      size="xs"
                      uppercase
                      letterSpacing="widest"
                      color={activeTab === tab.id ? 'text-primary-accent' : 'text-gray-500'}
                    >
                      {tab.label}
                    </Text>
                    {activeTab === tab.id && (
                      <Box 
                        position="absolute" 
                        bottom="-1px" 
                        left="0" 
                        right="0" 
                        h="2px" 
                        bg="primary-accent" 
                      />
                    )}
                  </Box>
                )
              ))}
            </Stack>
          </Box>

          <Box>
            {activeTab === 'overview' && (
              <Stack gap={8}>
                <Grid cols={12} gap={8}>
                  <GridItem colSpan={12} lgSpan={8}>
                    <Stack gap={8}>
                      <Box border borderColor="outline-steel" bg="surface-charcoal" bgOpacity={0.3} p={6}>
                        <Text size="xs" weight="bold" color="text-gray-400" uppercase>Mission Statement</Text>
                        <Text color="text-gray-300" leading="relaxed" size="sm" block mt={4}>
                          {team.description || 'No description provided.'}
                        </Text>
                      </Box>

                      <Box>
                        <Text size="xs" weight="bold" color="text-gray-400" uppercase mb={4} block>Recent Operations</Text>
                        <Box py={12} border borderStyle="dashed" borderColor="outline-steel" bg="surface-charcoal" bgOpacity={0.1} textAlign="center">
                          <Text color="text-gray-600" font="mono" size="xs">NO RECENT TELEMETRY DATA</Text>
                        </Box>
                      </Box>
                    </Stack>
                  </GridItem>

                  <GridItem colSpan={12} lgSpan={4}>
                    <Stack gap={6}>
                      <Box border borderColor="outline-steel" bg="surface-charcoal" bgOpacity={0.5} p={6}>
                        <Text size="xs" weight="bold" color="text-gray-400" uppercase mb={4} block>Performance Metrics</Text>
                        <Stack gap={4}>
                          <HorizontalStatItem label="Avg Rating" value="1450" color="text-primary-accent" />
                          <HorizontalStatItem label="Win Rate" value="12.5%" color="text-telemetry-aqua" />
                          <HorizontalStatItem label="Total Podiums" value="42" color="text-warning-amber" />
                        </Stack>
                      </Box>
                    </Stack>
                  </GridItem>
                </Grid>
              </Stack>
            )}

            {activeTab === 'roster' && (
              <Box>
                <Stack direction="row" align="center" justify="between" mb={6}>
                  <Text size="xs" weight="bold" color="text-gray-400" uppercase>Active Personnel</Text>
                  <Text size="xs" color="text-gray-500" font="mono">{viewData.memberships.length} UNITS ACTIVE</Text>
                </Stack>
                <TeamMembersTable 
                  members={viewData.memberships} 
                  isAdmin={viewData.isAdmin}
                  onRemoveMember={onRemoveMember}
                />
              </Box>
            )}

            {activeTab === 'standings' && (
              <TeamStandingsPanel standings={[]} /> // Mocked for now as in original
            )}

            {activeTab === 'admin' && viewData.isAdmin && (
              <TeamAdmin team={team} onUpdate={onUpdate} />
            )}
          </Box>
        </Stack>
      </Container>
    </Box>
  );
}
