'use client';

import Breadcrumbs from '@/components/layout/Breadcrumbs';
import SponsorInsightsCard from '@/components/sponsors/SponsorInsightsCard';
import { SlotTemplates } from '@/components/sponsors/SlotTemplates';
import { useSponsorMode } from '@/components/sponsors/useSponsorMode';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Image from 'next/image';

import JoinTeamButton from '@/components/teams/JoinTeamButton';
import TeamAdmin from '@/components/teams/TeamAdmin';
import TeamRoster from '@/components/teams/TeamRoster';
import TeamStandings from '@/components/teams/TeamStandings';
import StatItem from '@/components/teams/StatItem';
import { getMediaUrl } from '@/lib/utilities/media';
import PlaceholderImage from '@/components/ui/PlaceholderImage';
import type { TeamDetailViewData } from '@/lib/view-data/TeamDetailViewData';

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

// ============================================================================
// TEMPLATE PROPS
// ============================================================================

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;
}

// ============================================================================
// MAIN TEMPLATE COMPONENT
// ============================================================================

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

  // Show loading state
  if (loading) {
    return (
      <div className="max-w-6xl mx-auto">
        <div className="text-center text-gray-400">Loading team...</div>
      </div>
    );
  }

  // Show not found state
  if (!viewData.team) {
    return (
      <div className="max-w-6xl mx-auto">
        <Card>
          <div className="text-center py-12">
            <h2 className="text-2xl font-bold text-white mb-2">Team Not Found</h2>
            <p className="text-gray-400 mb-6">
              The team you're looking for doesn't exist or has been disbanded.
            </p>
            <Button variant="primary" onClick={onGoBack}>
              Go Back
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  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 (
    <div className="max-w-6xl mx-auto">
      {/* Breadcrumb */}
      <Breadcrumbs
        items={[
          { label: 'Home', href: '/' },
          { label: 'Teams', href: '/teams' },
          { label: viewData.team.name }
        ]}
      />

      {/* Sponsor Insights Card - Consistent placement at top */}
      {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}
        />
      )}

      <Card className="mb-6">
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-6">
            <div className="w-24 h-24 bg-charcoal-outline rounded-lg flex items-center justify-center flex-shrink-0 overflow-hidden">
              <Image
                src={getMediaUrl('team-logo', viewData.team.id)}
                alt={viewData.team.name}
                width={96}
                height={96}
                className="w-full h-full object-cover"
              />
            </div>
            
            <div>
              <div className="flex items-center gap-3 mb-2">
                <h1 className="text-3xl font-bold text-white">{viewData.team.name}</h1>
                {viewData.team.tag && (
                  <span className="px-2 py-0.5 rounded-full text-xs bg-charcoal-outline text-gray-300">
                    [{viewData.team.tag}]
                  </span>
                )}
              </div>

              <p className="text-gray-300 mb-4 max-w-2xl">{viewData.team.description}</p>

              <div className="flex items-center gap-4 text-sm text-gray-400">
                <span>{viewData.memberships.length} {viewData.memberships.length === 1 ? 'member' : 'members'}</span>
                {viewData.team.category && (
                  <span className="flex items-center gap-1 text-purple-400">
                    <span className="w-2 h-2 rounded-full bg-purple-400"></span>
                    {viewData.team.category}
                  </span>
                )}
                {viewData.team.createdAt && (
                  <span>
                    Founded {new Date(viewData.team.createdAt).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                  </span>
                )}
                {viewData.team.leagues && viewData.team.leagues.length > 0 && (
                  <span>
                    Active in {viewData.team.leagues.length} {viewData.team.leagues.length === 1 ? 'league' : 'leagues'}
                  </span>
                )}
              </div>
            </div>
          </div>

          <JoinTeamButton teamId={viewData.team.id} onUpdate={onUpdate} />
        </div>
      </Card>

      <div className="mb-6">
        <div className="flex items-center gap-2 border-b border-charcoal-outline">
          {visibleTabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => onTabChange(tab.id)}
              className={`
                px-4 py-3 font-medium transition-all relative
                ${activeTab === tab.id
                  ? 'text-primary-blue'
                  : 'text-gray-400 hover:text-white'
                }
              `}
            >
              {tab.label}
              {activeTab === tab.id && (
                <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary-blue" />
              )}
            </button>
          ))}
        </div>
      </div>

      <div>
        {activeTab === 'overview' && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <Card className="lg:col-span-2">
                <h3 className="text-xl font-semibold text-white mb-4">About</h3>
                <p className="text-gray-300 leading-relaxed">{viewData.team.description}</p>
              </Card>

              <Card>
                <h3 className="text-xl font-semibold text-white mb-4">Quick Stats</h3>
                <div className="space-y-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"
                    />
                  )}
                </div>
              </Card>
            </div>

            <Card>
              <h3 className="text-xl font-semibold text-white mb-4">Recent Activity</h3>
              <div className="text-center py-8 text-gray-400">
                No recent activity to display
              </div>
            </Card>
          </div>
        )}

        {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} />
        )}
      </div>
    </div>
  );
}
