'use client';

import { Breadcrumbs } from '@/components/layout/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 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();

  // 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 (!viewData.team) {
    return (
      <Container size="md" py={12}>
        <Card>
          <Stack align="center" py={12} gap={6}>
            <Box style={{ textAlign: 'center' }}>
              <Heading level={1}>Team Not Found</Heading>
              <Text color="text-gray-400" block mt={2}>
                The team you're looking for doesn't exist or has been disbanded.
              </Text>
            </Box>
            <Button variant="primary" onClick={onGoBack}>
              Go Back
            </Button>
          </Stack>
        </Card>
      </Container>
    );
  }

  const tabs: { id: Tab; label: string; visible: boolean }[] = [
    { id: 'overview', label: 'Overview', visible: true },
    { id: 'roster', label: 'Roster', visible: true },
    { id: 'standings', label: 'Standings', visible: true },
    { id: 'admin', label: 'Admin', visible: viewData.isAdmin },
  ];

  const visibleTabs = tabs.filter(tab => tab.visible);

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

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

        <TeamHero 
          team={viewData.team} 
          memberCount={viewData.memberships.length} 
          onUpdate={onUpdate} 
        />

        {/* Tabs */}
        <Box style={{ borderBottom: '1px solid #262626' }}>
          <Stack direction="row" gap={6}>
            {visibleTabs.map((tab) => (
              <Box
                key={tab.id}
                onClick={() => onTabChange(tab.id)}
                pb={3}
                style={{ 
                  cursor: 'pointer',
                  borderBottom: activeTab === tab.id ? '2px solid #3b82f6' : '2px solid transparent',
                  color: activeTab === tab.id ? '#3b82f6' : '#9ca3af'
                }}
              >
                <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" style={{ lineHeight: 1.625 }}>{viewData.team.description}</Text>
                  </Card>
                </GridItem>

                <GridItem colSpan={12} lgSpan={4}>
                  <Card>
                    <Box mb={4}>
                      <Heading level={2}>Quick Stats</Heading>
                    </Box>
                    <Stack gap={3}>
                      <StatItem label="Members" value={viewData.memberships.length.toString()} color="text-primary-blue" />
                      {viewData.team.category && (
                        <StatItem label="Category" value={viewData.team.category} color="text-purple-400" />
                      )}
                      {viewData.team.leagues && viewData.team.leagues.length > 0 && (
                        <StatItem label="Leagues" value={viewData.team.leagues.length.toString()} color="text-green-400" />
                      )}
                      {viewData.team.createdAt && (
                        <StatItem
                          label="Founded"
                          value={new Date(viewData.team.createdAt).toLocaleDateString('en-US', {
                            month: 'short',
                            year: 'numeric',
                          })}
                          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 style={{ textAlign: 'center' }}>No recent activity to display</Text>
                </Box>
              </Card>
            </Stack>
          )}

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

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

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