'use client';

import { useState, useEffect, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Image from 'next/image';
import Link from 'next/link';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Breadcrumbs from '@/components/layout/Breadcrumbs';
import SponsorInsightsCard, { useSponsorMode, MetricBuilders, SlotTemplates } from '@/components/sponsors/SponsorInsightsCard';

import { TeamMembersPresenter } from '@/lib/presenters/TeamMembersPresenter';
import { TeamDetailsPresenter } from '@/lib/presenters/TeamDetailsPresenter';
import type { TeamDetailsViewModel } from '@core/racing/application/presenters/ITeamDetailsPresenter';
import TeamRoster from '@/components/teams/TeamRoster';
import TeamStandings from '@/components/teams/TeamStandings';
import TeamAdmin from '@/components/teams/TeamAdmin';
import JoinTeamButton from '@/components/teams/JoinTeamButton';

import { useEffectiveDriverId } from '@/lib/currentDriver';
import { Users, Trophy, TrendingUp, Star, Zap } from 'lucide-react';

type TeamRole = 'owner' | 'manager' | 'driver';

interface TeamMembership {
  driverId: string;
  role: TeamRole;
  joinedAt: Date;
}

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

export default function TeamDetailPage() {
  const params = useParams();
  const teamId = params.id as string;

  type TeamViewModel = TeamDetailsViewModel['team'];

  const [team, setTeam] = useState<TeamViewModel | null>(null);
  const [memberships, setMemberships] = useState<TeamMembership[]>([]);
  const [activeTab, setActiveTab] = useState<Tab>('overview');
  const [loading, setLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);
  const currentDriverId = useEffectiveDriverId();
  const isSponsorMode = useSponsorMode();

  const loadTeamData = useCallback(async () => {
    setLoading(true);
    try {
      const detailsUseCase = getGetTeamDetailsUseCase();
      const membersUseCase = getGetTeamMembersUseCase();

      const detailsPresenter = new TeamDetailsPresenter();
      await detailsUseCase.execute({ teamId, driverId: currentDriverId }, detailsPresenter);
      const detailsViewModel = detailsPresenter.getViewModel();

      if (!detailsViewModel) {
        setTeam(null);
        setMemberships([]);
        setIsAdmin(false);
        return;
      }

      const teamMembersPresenter = new TeamMembersPresenter();
      await membersUseCase.execute({ teamId }, teamMembersPresenter);
      const membersViewModel = teamMembersPresenter.getViewModel();

      const teamMemberships: TeamMembership[] = (membersViewModel?.members ?? []).map((m) => ({
        driverId: m.driverId,
        role: m.role as TeamRole,
        joinedAt: new Date(m.joinedAt),
      }));

      const adminStatus =
        teamMemberships.some(
          (m: TeamMembership) =>
            m.driverId === currentDriverId &&
            (m.role === 'owner' || m.role === 'manager'),
        ) ?? false;

      setTeam(detailsViewModel.team);
      setMemberships(teamMemberships);
      setIsAdmin(adminStatus);
    } finally {
      setLoading(false);
    }
  }, [teamId, currentDriverId]);

  useEffect(() => {
    void loadTeamData();
  }, [loadTeamData]);

  const handleUpdate = () => {
    loadTeamData();
  };

  const handleRemoveMember = async (driverId: string) => {
    if (!confirm('Are you sure you want to remove this member?')) {
      return;
    }

    try {
      const membershipRepo = getTeamMembershipRepository();
      const performer = await membershipRepo.getMembership(teamId, currentDriverId);
      if (!performer || (performer.role !== 'owner' && performer.role !== 'manager')) {
        throw new Error('Only owners or managers can remove members');
      }

      const membership = await membershipRepo.getMembership(teamId, driverId);
      if (!membership) {
        throw new Error('Member not found');
      }
      if (membership.role === 'owner') {
        throw new Error('Cannot remove the team owner');
      }

      await membershipRepo.removeMembership(teamId, driverId);
      handleUpdate();
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to remove member');
    }
  };

  const handleChangeRole = async (driverId: string, newRole: TeamRole) => {
    try {
      const membershipRepo = getTeamMembershipRepository();
      const performer = await membershipRepo.getMembership(teamId, currentDriverId);
      if (!performer || (performer.role !== 'owner' && performer.role !== 'manager')) {
        throw new Error('Only owners or managers can update roles');
      }

      const membership = await membershipRepo.getMembership(teamId, driverId);
      if (!membership) {
        throw new Error('Member not found');
      }
      if (membership.role === 'owner') {
        throw new Error('Cannot change the owner role');
      }

      await membershipRepo.saveMembership({
        ...membership,
        role: newRole,
      });
      handleUpdate();
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to change role');
    }
  };

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

  if (!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={() => window.history.back()}>
              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: isAdmin },
  ];

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

  // Build sponsor insights for team
  const teamMetrics = [
    MetricBuilders.members(memberships.length),
    MetricBuilders.reach(memberships.length * 15),
    MetricBuilders.races(team.leagues.length * 8),
    MetricBuilders.engagement(82),
  ];

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

      {/* Sponsor Insights Card - Consistent placement at top */}
      {isSponsorMode && team && (
        <SponsorInsightsCard
          entityType="team"
          entityId={team.id}
          entityName={team.name}
          tier="standard"
          metrics={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={getImageService().getTeamLogo(team.id)}
                alt={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">{team.name}</h1>
                <span className="px-3 py-1 bg-charcoal-outline text-gray-300 rounded-full text-sm font-medium">
                  {team.tag}
                </span>
              </div>
              
              <p className="text-gray-300 mb-4 max-w-2xl">{team.description}</p>
              
              <div className="flex items-center gap-4 text-sm text-gray-400">
                <span>{memberships.length} {memberships.length === 1 ? 'member' : 'members'}</span>
                <span>•</span>
                <span>Created {new Date(team.createdAt).toLocaleDateString()}</span>
                {team.leagues.length > 0 && (
                  <>
                    <span>•</span>
                    <span>{team.leagues.length} {team.leagues.length === 1 ? 'league' : 'leagues'}</span>
                  </>
                )}
              </div>
            </div>
          </div>

          <JoinTeamButton teamId={teamId} onUpdate={handleUpdate} />
        </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={() => setActiveTab(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">{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={memberships.length.toString()} color="text-primary-blue" />
                  <StatItem label="Leagues" value={team.leagues.length.toString()} color="text-green-400" />
                  <StatItem label="Founded" value={new Date(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={teamId}
            memberships={memberships}
            isAdmin={isAdmin}
            onRemoveMember={handleRemoveMember}
            onChangeRole={handleChangeRole}
          />
        )}

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

        {activeTab === 'admin' && isAdmin && (
          <TeamAdmin team={team} onUpdate={handleUpdate} />
        )}
      </div>
    </div>
  );
}

function StatItem({ label, value, color }: { label: string; value: string; color: string }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-gray-400 text-sm">{label}</span>
      <span className={`font-semibold ${color}`}>{value}</span>
    </div>
  );
}