'use client';

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

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 { useServices } from '@/lib/services/ServiceProvider';
import { TeamDetailsViewModel } from '@/lib/view-models/TeamDetailsViewModel';
import { TeamMemberViewModel } from '@/lib/view-models/TeamMemberViewModel';
import { getMediaUrl } from '@/lib/utilities/media';
import PlaceholderImage from '@/components/ui/PlaceholderImage';

import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';

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

export default function TeamDetailPage() {
    const params = useParams();
    const teamId = params.id as string;
    const { teamService, mediaService } = useServices();

    const [team, setTeam] = useState<TeamDetailsViewModel | null>(null);
    const [memberships, setMemberships] = useState<TeamMemberViewModel[]>([]);
    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 teamDetails = await teamService.getTeamDetails(teamId, currentDriverId);

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

      const teamMembers = await teamService.getTeamMembers(teamId, currentDriverId, teamDetails.ownerId);

      const adminStatus = teamDetails.isOwner ||
        teamMembers.some((m) => m.driverId === currentDriverId && (m.role === 'manager' || m.role === 'owner'));

      setTeam(teamDetails);
      setMemberships(teamMembers);
      setIsAdmin(adminStatus);
    } finally {
      setLoading(false);
    }
  }, [teamId, currentDriverId, teamService]);

  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 performer = await teamService.getMembership(teamId, currentDriverId);
      if (!performer || (performer.role !== 'owner' && performer.role !== 'manager')) {
        throw new Error('Only owners or admins can remove members');
      }

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

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

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

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

      // Convert 'admin' to 'manager' for the service
      const serviceRole = newRole === 'admin' ? 'manager' : newRole;
      await teamService.updateMembership(teamId, driverId, serviceRole);
      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 using real membership and league data
  const leagueCount = team.leagues?.length ?? 0;
  const teamMetrics = [
    MetricBuilders.members(memberships.length),
    MetricBuilders.reach(memberships.length * 15),
    MetricBuilders.races(leagueCount),
    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={getMediaUrl('team-logo', 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>
                {team.tag && (
                  <span className="px-2 py-0.5 rounded-full text-xs bg-charcoal-outline text-gray-300">
                    [{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>
                {team.category && (
                  <span className="flex items-center gap-1 text-purple-400">
                    <span className="w-2 h-2 rounded-full bg-purple-400"></span>
                    {team.category}
                  </span>
                )}
                {team.createdAt && (
                  <span>
                    Founded {new Date(team.createdAt).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                  </span>
                )}
                {leagueCount > 0 && (
                  <span>
                    Active in {leagueCount} {leagueCount === 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" />
                  {team.category && (
                    <StatItem label="Category" value={team.category} color="text-purple-400" />
                  )}
                  {leagueCount > 0 && (
                    <StatItem label="Leagues" value={leagueCount.toString()} color="text-green-400" />
                  )}
                  {team.createdAt && (
                    <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>
  );
}