'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams, useSearchParams } from 'next/navigation';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import JoinLeagueButton from '@/components/leagues/JoinLeagueButton';
import LeagueMembers from '@/components/leagues/LeagueMembers';
import LeagueSchedule from '@/components/leagues/LeagueSchedule';
import LeagueAdmin from '@/components/leagues/LeagueAdmin';
import StandingsTable from '@/components/leagues/StandingsTable';
import LeagueScoringTab from '@/components/leagues/LeagueScoringTab';
import DriverIdentity from '@/components/drivers/DriverIdentity';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';
import { League } from '@gridpilot/racing/domain/entities/League';
import { Driver } from '@gridpilot/racing/domain/entities/Driver';
import type { DriverDTO } from '@gridpilot/racing/application/dto/DriverDTO';
import type { LeagueDriverSeasonStatsDTO } from '@gridpilot/racing/application/dto/LeagueDriverSeasonStatsDTO';
import type { LeagueScoringConfigDTO } from '@gridpilot/racing/application/dto/LeagueScoringConfigDTO';
import { EntityMappers } from '@gridpilot/racing/application/mappers/EntityMappers';
import {
  getLeagueRepository,
  getRaceRepository,
  getDriverRepository,
  getGetLeagueDriverSeasonStatsQuery,
  getGetLeagueScoringConfigQuery,
  getDriverStats,
  getAllDriverRankings,
} from '@/lib/di-container';
import { getMembership, getLeagueMembers, isOwnerOrAdmin } from '@/lib/leagueMembership';
import { useEffectiveDriverId } from '@/lib/currentDriver';

export default function LeagueDetailPage() {
  const router = useRouter();
  const params = useParams();
  const leagueId = params.id as string;

  const [league, setLeague] = useState<League | null>(null);
  const [owner, setOwner] = useState<Driver | null>(null);
  const [standings, setStandings] = useState<LeagueDriverSeasonStatsDTO[]>([]);
  const [drivers, setDrivers] = useState<DriverDTO[]>([]);
  const [scoringConfig, setScoringConfig] = useState<LeagueScoringConfigDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<
    'overview' | 'schedule' | 'standings' | 'scoring' | 'admin'
  >('overview');
  const [refreshKey, setRefreshKey] = useState(0);

  const currentDriverId = useEffectiveDriverId();
  const membership = getMembership(leagueId, currentDriverId);
  const isAdmin = isOwnerOrAdmin(leagueId, currentDriverId);
  const searchParams = useSearchParams();

  const loadLeagueData = async () => {
    try {
      const leagueRepo = getLeagueRepository();
      const raceRepo = getRaceRepository();
      const driverRepo = getDriverRepository();

      const leagueData = await leagueRepo.findById(leagueId);
      
      if (!leagueData) {
        setError('League not found');
        setLoading(false);
        return;
      }

      setLeague(leagueData);

      // Load owner data
      const ownerData = await driverRepo.findById(leagueData.ownerId);
      setOwner(ownerData);

      // Load standings via rich season stats query
      const getLeagueDriverSeasonStatsQuery = getGetLeagueDriverSeasonStatsQuery();
      const leagueStandings = await getLeagueDriverSeasonStatsQuery.execute({ leagueId });
      setStandings(leagueStandings);

      // Load scoring configuration for the active season
      const getLeagueScoringConfigQuery = getGetLeagueScoringConfigQuery();
      const scoring = await getLeagueScoringConfigQuery.execute({ leagueId });
      setScoringConfig(scoring);

      // Load all drivers for standings and map to DTOs for UI components
      const allDrivers = await driverRepo.findAll();
      const driverDtos: DriverDTO[] = allDrivers
        .map((driver) => EntityMappers.toDriverDTO(driver))
        .filter((dto): dto is DriverDTO => dto !== null);

      setDrivers(driverDtos);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load league');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadLeagueData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [leagueId]);

  useEffect(() => {
    const initialTab = searchParams?.get('tab');
    if (!initialTab) {
      return;
    }

    if (
      initialTab === 'overview' ||
      initialTab === 'schedule' ||
      initialTab === 'standings' ||
      initialTab === 'scoring' ||
      initialTab === 'admin'
    ) {
      setActiveTab(initialTab as typeof activeTab);
    }
  }, [searchParams]);

  const handleMembershipChange = () => {
    setRefreshKey(prev => prev + 1);
    loadLeagueData();
  };

  const driversById = useMemo(() => {
    const map: Record<string, DriverDTO> = {};
    for (const d of drivers) {
      map[d.id] = d;
    }
    return map;
  }, [drivers]);

  const leagueMemberships = getLeagueMembers(leagueId);
  const ownerMembership = leagueMemberships.find((m) => m.role === 'owner') ?? null;
  const adminMemberships = leagueMemberships.filter((m) => m.role === 'admin');

  const buildDriverSummary = (driverId: string) => {
    const driverDto = driversById[driverId];
    if (!driverDto) {
      return null;
    }

    const stats = getDriverStats(driverDto.id);
    const allRankings = getAllDriverRankings();

    let rating: number | null = stats?.rating ?? null;
    let rank: number | null = null;

    if (stats) {
      if (typeof stats.overallRank === 'number' && stats.overallRank > 0) {
        rank = stats.overallRank;
      } else {
        const indexInGlobal = allRankings.findIndex(
          (stat) => stat.driverId === stats.driverId,
        );
        if (indexInGlobal !== -1) {
          rank = indexInGlobal + 1;
        }
      }

      if (rating === null) {
        const globalEntry = allRankings.find(
          (stat) => stat.driverId === stats.driverId,
        );
        if (globalEntry) {
          rating = globalEntry.rating;
        }
      }
    }

    return {
      driver: driverDto,
      rating,
      rank,
    };
  };

  return loading ? (
    <div className="text-center text-gray-400">Loading league...</div>
  ) : error || !league ? (
    <Card className="text-center py-12">
      <div className="text-warning-amber mb-4">
        {error || 'League not found'}
      </div>
      <Button
        variant="secondary"
        onClick={() => router.push('/leagues')}
      >
        Back to Leagues
      </Button>
    </Card>
  ) : (
    <>
      {/* Action Card */}
      {!membership && (
        <Card className="mb-6">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-semibold text-white mb-2">Join This League</h3>
              <p className="text-gray-400 text-sm">Become a member to participate in races and track your progress</p>
            </div>
            <div className="w-48">
              <JoinLeagueButton
                leagueId={leagueId}
                onMembershipChange={handleMembershipChange}
              />
            </div>
          </div>
        </Card>
      )}

      {/* Overview section switcher (in-page, not primary tabs) */}
      <div className="mb-6">
        <div className="inline-flex flex-wrap gap-2 rounded-full bg-iron-gray/60 px-2 py-1">
          <button
            onClick={() => setActiveTab('overview')}
            className={`px-3 py-1 text-xs font-medium rounded-full transition-colors ${
              activeTab === 'overview'
                ? 'bg-primary-blue text-white'
                : 'text-gray-300 hover:text-white hover:bg-charcoal-outline/80'
            }`}
          >
            Overview
          </button>
          <button
            onClick={() => setActiveTab('schedule')}
            className={`px-3 py-1 text-xs font-medium rounded-full transition-colors ${
              activeTab === 'schedule'
                ? 'bg-primary-blue text-white'
                : 'text-gray-300 hover:text-white hover:bg-charcoal-outline/80'
            }`}
          >
            Schedule
          </button>
          <button
            onClick={() => setActiveTab('standings')}
            className={`px-3 py-1 text-xs font-medium rounded-full transition-colors ${
              activeTab === 'standings'
                ? 'bg-primary-blue text-white'
                : 'text-gray-300 hover:text-white hover:bg-charcoal-outline/80'
            }`}
          >
            Standings
          </button>
          <button
            onClick={() => setActiveTab('scoring')}
            className={`px-3 py-1 text-xs font-medium rounded-full transition-colors ${
              activeTab === 'scoring'
                ? 'bg-primary-blue text-white'
                : 'text-gray-300 hover:text-white hover:bg-charcoal-outline/80'
            }`}
          >
            Scoring
          </button>
          {isAdmin && (
            <button
              onClick={() => setActiveTab('admin')}
              className={`px-3 py-1 text-xs font-medium rounded-full transition-colors ${
                activeTab === 'admin'
                  ? 'bg-primary-blue text-white'
                  : 'text-gray-300 hover:text-white hover:bg-charcoal-outline/80'
              }`}
            >
              Admin
            </button>
          )}
        </div>
      </div>

      {/* Tab Content */}
      {activeTab === 'overview' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* League Info */}
          <Card className="lg:col-span-2">
            <h2 className="text-xl font-semibold text-white mb-4">League Information</h2>
            
            <div className="space-y-4">
              <div>
                <label className="text-sm text-gray-500">Created</label>
                <p className="text-white">
                  {new Date(league.createdAt).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}
                </p>
              </div>

              <div className="pt-4 border-t border-charcoal-outline">
                <h3 className="text-white font-medium mb-3">At a glance</h3>
                
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                  <div>
                    <h4 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">
                      Structure
                    </h4>
                    <p className="text-gray-200">
                      Solo • {league.settings.maxDrivers ?? 32} drivers
                    </p>
                  </div>
                  <div>
                    <h4 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">
                      Schedule
                    </h4>
                    <p className="text-gray-200">
                      {`? rounds • 30 min Qualifying • ${
                        typeof league.settings.sessionDuration === 'number'
                          ? league.settings.sessionDuration
                          : 40
                      } min Races`}
                    </p>
                  </div>
                  <div>
                    <h4 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">
                      Scoring & drops
                    </h4>
                    <p className="text-gray-200">
                      {league.settings.pointsSystem.toUpperCase()}
                    </p>
                  </div>
                </div>
              </div>

              {league.socialLinks && (
                <div className="pt-4 border-t border-charcoal-outline">
                  <h3 className="text-white font-medium mb-3">Community & Social</h3>
                  <div className="flex flex-wrap gap-3 text-sm">
                    {league.socialLinks.discordUrl && (
                      <a
                        href={league.socialLinks.discordUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center gap-1 rounded-full border border-primary-blue/40 bg-primary-blue/10 px-3 py-1 text-primary-blue hover:bg-primary-blue/20 transition-colors"
                      >
                        <span>Discord</span>
                      </a>
                    )}
                    {league.socialLinks.youtubeUrl && (
                      <a
                        href={league.socialLinks.youtubeUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center gap-1 rounded-full border border-red-500/40 bg-red-500/10 px-3 py-1 text-red-400 hover:bg-red-500/20 transition-colors"
                      >
                        <span>YouTube</span>
                      </a>
                    )}
                    {league.socialLinks.websiteUrl && (
                      <a
                        href={league.socialLinks.websiteUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center gap-1 rounded-full border border-charcoal-outline bg-iron-gray/70 px-3 py-1 text-gray-100 hover:bg-iron-gray transition-colors"
                      >
                        <span>Website</span>
                      </a>
                    )}
                  </div>
                </div>
              )}

              <div className="pt-4 border-t border-charcoal-outline">
                <h3 className="text-white font-medium mb-3">Management</h3>
                <div className="space-y-4">
                  {ownerMembership && (
                    <div>
                      <label className="text-sm text-gray-500 block mb-2">Owner</label>
                      {buildDriverSummary(ownerMembership.driverId) ? (
                        <DriverSummaryPill
                          driver={buildDriverSummary(ownerMembership.driverId)!.driver}
                          rating={buildDriverSummary(ownerMembership.driverId)!.rating}
                          rank={buildDriverSummary(ownerMembership.driverId)!.rank}
                        />
                      ) : (
                        <p className="text-sm text-gray-500">
                          {owner ? owner.name : `ID: ${league.ownerId.slice(0, 8)}...`}
                        </p>
                      )}
                    </div>
                  )}

                  {adminMemberships.length > 0 && (
                    <div>
                      <label className="text-sm text-gray-500 block mb-2">Admins</label>
                      <div className="space-y-2">
                        {adminMemberships.map((membership) => {
                          const driverDto = driversById[membership.driverId];
                          const summary = buildDriverSummary(membership.driverId);
                          const meta =
                            summary && summary.rating !== null
                              ? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
                              : null;

                          return (
                            <div
                              key={membership.driverId}
                              className="flex items-center justify-between gap-3"
                            >
                              {driverDto ? (
                                <DriverIdentity
                                  driver={driverDto}
                                  href={`/drivers/${membership.driverId}?from=league-management&leagueId=${leagueId}`}
                                  contextLabel="Admin"
                                  meta={meta}
                                  size="sm"
                                />
                              ) : (
                                <span className="text-sm text-gray-400">Unknown admin</span>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {adminMemberships.length === 0 && !ownerMembership && (
                    <p className="text-sm text-gray-500">
                      Management roles have not been configured for this league yet.
                    </p>
                  )}
                </div>
              </div>
            </div>
          </Card>

          {/* Quick Actions */}
          <Card>
            <h2 className="text-xl font-semibold text-white mb-4">Quick Actions</h2>
            
            <div className="space-y-3">
              {membership ? (
                <>
                  <Button
                    variant="primary"
                    className="w-full"
                    onClick={() => setActiveTab('schedule')}
                  >
                    View Schedule
                  </Button>
                  <Button
                    variant="secondary"
                    className="w-full"
                    onClick={() => setActiveTab('standings')}
                  >
                    View Standings
                  </Button>
                  <JoinLeagueButton
                    leagueId={leagueId}
                    onMembershipChange={handleMembershipChange}
                  />
                </>
              ) : (
                <JoinLeagueButton
                  leagueId={leagueId}
                  onMembershipChange={handleMembershipChange}
                />
              )}
            </div>
          </Card>
        </div>
      )}

      {activeTab === 'schedule' && (
        <Card>
          <LeagueSchedule leagueId={leagueId} key={refreshKey} />
        </Card>
      )}

      {activeTab === 'standings' && (
        <Card>
          <h2 className="text-xl font-semibold text-white mb-4">Standings</h2>
          <StandingsTable standings={standings} drivers={drivers} leagueId={leagueId} />
        </Card>
      )}

      {activeTab === 'scoring' && (
        <Card>
          <h2 className="text-xl font-semibold text-white mb-4">Scoring</h2>
          <LeagueScoringTab
            scoringConfig={scoringConfig}
            practiceMinutes={20}
            qualifyingMinutes={30}
            sprintRaceMinutes={20}
            mainRaceMinutes={
              typeof league.settings.sessionDuration === 'number'
                ? league.settings.sessionDuration
                : 40
            }
          />
        </Card>
      )}

      {activeTab === 'admin' && isAdmin && (
        <LeagueAdmin
          league={league}
          onLeagueUpdate={handleMembershipChange}
          key={refreshKey}
        />
      )}
    </>
  );
}