'use client';

import React from 'react';
import { Breadcrumbs } from '@/ui/Breadcrumbs';
import { SlotTemplates } from '@/components/sponsors/SlotTemplates';
import { SponsorInsightsCard } from '@/components/sponsors/SponsorInsightsCard';
import { useSponsorMode } from '@/hooks/sponsor/useSponsorMode';
import { Box } from '@/ui/Box';
import { Button } from '@/ui/Button';
import { Card } from '@/ui/Card';
import { Container } from '@/ui/Container';
import { Grid } from '@/ui/Grid';
import { GridItem } from '@/ui/GridItem';
import { Heading } from '@/ui/Heading';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { HorizontalStatItem } from '@/ui/HorizontalStatItem';
import { DateDisplay } from '@/lib/display-objects/DateDisplay';

import { TeamAdmin } from '@/components/teams/TeamAdmin';
import { TeamHero } from '@/components/teams/TeamHero';
import { TeamRoster } from '@/components/teams/TeamRoster';
import { TeamStandings } from '@/components/teams/TeamStandings';
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;
  onChangeRole: (driverId: string, newRole: 'owner' | 'admin' | 'member') => void;
  onGoBack: () => void;
}

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

  const team = viewData.team;

  // Show loading state
  if (loading) {
    return (
      <Container size="lg" py={12}>
        <Stack align="center">
          <Text color="text-gray-400">Loading team...</Text>
        </Stack>
      </Container>
    );
  }

  // Show not found state
  if (!team) {
    return (
      <Container size="md" py={12}>
        <Card>
          <Stack align="center" py={12} gap={6}>
            <Box textAlign="center">
              <Heading level={1}>Team Not Found</Heading>
              <Text color="text-gray-400" block mt={2}>
                The team you&apos;re looking for doesn&apos;t exist or has been disbanded.
              </Text>
            </Box>
            <Button variant="primary" onClick={onGoBack}>
              Go Back
            </Button>
          </Stack>
        </Card>
      </Container>
    );
  }

  return (
    <Container size="lg" py={8}>
      <Stack gap={6}>
        {/* Breadcrumb */}
        <Breadcrumbs
          items={[
            { label: 'Home', href: '/' },
            { label: 'Teams', href: '/teams' },
            { label: team.name }
          ]}
        />

        {/* Sponsor Insights Card */}
        {isSponsorMode && team && (
          <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}
          />
        )}

        <TeamHero 
          team={{
            ...team,
            leagues: team.leagues.map(id => ({ id }))
          }} 
          memberCount={viewData.memberships.length} 
          onUpdate={onUpdate} 
        />

        {/* Tabs */}
        <Box borderBottom={true} borderColor="border-charcoal-outline">
          <Stack direction="row" gap={6}>
            {viewData.tabs.map((tab) => (
              tab.visible && (
                <Box
                  key={tab.id}
                  onClick={() => onTabChange(tab.id)}
                  pb={3}
                  cursor="pointer"
                  borderBottom={activeTab === tab.id ? '2px solid' : '2px solid'}
                  borderColor={activeTab === tab.id ? 'border-primary-blue' : 'border-transparent'}
                  color={activeTab === tab.id ? 'text-primary-blue' : 'text-gray-400'}
                >
                  <Text weight="medium">{tab.label}</Text>
                </Box>
              )
            ))}
          </Stack>
        </Box>

        <Box>
          {activeTab === 'overview' && (
            <Stack gap={6}>
              <Grid cols={12} gap={6}>
                <GridItem colSpan={12} lgSpan={8}>
                  <Card>
                    <Box mb={4}>
                      <Heading level={2}>About</Heading>
                    </Box>
                    <Text color="text-gray-300" leading="relaxed">{team.description}</Text>
                  </Card>
                </GridItem>

                <GridItem colSpan={12} lgSpan={4}>
                  <Card>
                    <Box mb={4}>
                      <Heading level={2}>Quick Stats</Heading>
                    </Box>
                    <Stack gap={3}>
                      <HorizontalStatItem label="Members" value={viewData.memberships.length.toString()} color="text-primary-blue" />
                      {team.category && (
                        <HorizontalStatItem label="Category" value={team.category} color="text-purple-400" />
                      )}
                      {team.leagues && team.leagues.length > 0 && (
                        <HorizontalStatItem label="Leagues" value={team.leagues.length.toString()} color="text-green-400" />
                      )}
                      {team.createdAt && (
                        <HorizontalStatItem
                          label="Founded"
                          value={DateDisplay.formatMonthYear(team.createdAt)}
                          color="text-gray-300"
                        />
                      )}
                    </Stack>
                  </Card>
                </GridItem>
              </Grid>

              <Card>
                <Box mb={4}>
                  <Heading level={2}>Recent Activity</Heading>
                </Box>
                <Box py={8}>
                  <Text color="text-gray-400" block align="center">No recent activity to display</Text>
                </Box>
              </Card>
            </Stack>
          )}

          {activeTab === 'roster' && (
            <TeamRoster
              teamId={team.id}
              memberships={viewData.memberships}
              isAdmin={viewData.isAdmin}
              onRemoveMember={onRemoveMember}
              onChangeRole={onChangeRole}
            />
          )}

          {activeTab === 'standings' && (
            <TeamStandings teamId={team.id} leagues={team.leagues} />
          )}

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