'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import JoinLeagueButton from '@/components/leagues/JoinLeagueButton';
import LeagueActivityFeed from '@/components/leagues/LeagueActivityFeed';
import DriverIdentity from '@/components/drivers/DriverIdentity';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';
import {
  League,
  Driver,
  EntityMappers,
  type DriverDTO,
  type LeagueScoringConfigDTO,
} from '@gridpilot/racing';
import {
  getLeagueRepository,
  getRaceRepository,
  getDriverRepository,
  getGetLeagueScoringConfigQuery,
  getDriverStats,
  getAllDriverRankings,
  getGetLeagueStatsQuery,
} from '@/lib/di-container';
import { Zap, Users, Trophy, Calendar } from 'lucide-react';
import { getMembership, getLeagueMembers } from '@/lib/leagueMembership';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import { getLeagueRoleDisplay } from '@/lib/leagueRoles';

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 [drivers, setDrivers] = useState<DriverDTO[]>([]);
  const [scoringConfig, setScoringConfig] = useState<LeagueScoringConfigDTO | null>(null);
  const [averageSOF, setAverageSOF] = useState<number | null>(null);
  const [completedRacesCount, setCompletedRacesCount] = useState<number>(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshKey, setRefreshKey] = useState(0);

  const currentDriverId = useEffectiveDriverId();
  const membership = getMembership(leagueId, currentDriverId);

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

      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 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);
      
      // Load league stats including average SOF from application query
      const leagueStats = await leagueStatsQuery.execute({ leagueId });
      if (leagueStats) {
        setAverageSOF(leagueStats.averageSOF);
        setCompletedRacesCount(leagueStats.completedRaces);
      } else {
        // Fallback: count completed races manually
        const leagueRaces = await raceRepo.findByLeagueId(leagueId);
        const completedRaces = leagueRaces.filter(r => r.status === 'completed');
        setCompletedRacesCount(completedRaces.length);
      }
    } 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]);

  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 stewardMemberships = leagueMemberships.filter((m) => m.role === 'steward');

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

      {/* League Overview - Activity Center with Info Sidebar */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Center - Activity Feed */}
        <div className="lg:col-span-2 space-y-6">
          <Card>
            <h2 className="text-xl font-semibold text-white mb-6">Recent Activity</h2>
            <LeagueActivityFeed leagueId={leagueId} limit={20} />
          </Card>
        </div>

        {/* Right Sidebar - League Info */}
        <div className="space-y-6">
          {/* League Info - Combined */}
          <Card>
            <h3 className="text-lg font-semibold text-white mb-4">About</h3>
            
            {/* Stats Grid */}
            <div className="grid grid-cols-3 gap-3 mb-4">
              <div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
                <div className="text-xl font-bold text-white">{leagueMemberships.length}</div>
                <div className="text-xs text-gray-500">Members</div>
              </div>
              <div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
                <div className="text-xl font-bold text-white">{completedRacesCount}</div>
                <div className="text-xs text-gray-500">Races</div>
              </div>
              <div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
                <div className="text-xl font-bold text-warning-amber">{averageSOF ?? '—'}</div>
                <div className="text-xs text-gray-500">Avg SOF</div>
              </div>
            </div>

            {/* Details */}
            <div className="space-y-2 text-sm">
              <div className="flex items-center justify-between py-1.5 border-b border-charcoal-outline/50">
                <span className="text-gray-500">Structure</span>
                <span className="text-white">Solo • {league.settings.maxDrivers ?? 32} max</span>
              </div>
              <div className="flex items-center justify-between py-1.5 border-b border-charcoal-outline/50">
                <span className="text-gray-500">Scoring</span>
                <span className="text-white">{scoringConfig?.scoringPresetName ?? 'Standard'}</span>
              </div>
              <div className="flex items-center justify-between py-1.5">
                <span className="text-gray-500">Created</span>
                <span className="text-white">
                  {new Date(league.createdAt).toLocaleDateString('en-US', {
                    month: 'short',
                    year: 'numeric'
                  })}
                </span>
              </div>
            </div>

            {league.socialLinks && (
              <div className="mt-4 pt-4 border-t border-charcoal-outline">
                <div className="flex flex-wrap gap-2">
                  {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-2 py-1 text-xs text-primary-blue hover:bg-primary-blue/20 transition-colors"
                    >
                      Discord
                    </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-2 py-1 text-xs text-red-400 hover:bg-red-500/20 transition-colors"
                    >
                      YouTube
                    </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-2 py-1 text-xs text-gray-100 hover:bg-iron-gray transition-colors"
                    >
                      Website
                    </a>
                  )}
                </div>
              </div>
            )}
          </Card>

          {/* Management */}
          {(ownerMembership || adminMemberships.length > 0 || stewardMemberships.length > 0) && (
            <Card>
              <h3 className="text-lg font-semibold text-white mb-4">Management</h3>
              <div className="space-y-2">
                {ownerMembership && (() => {
                  const driverDto = driversById[ownerMembership.driverId];
                  const summary = buildDriverSummary(ownerMembership.driverId);
                  const roleDisplay = getLeagueRoleDisplay('owner');
                  const meta = summary && summary.rating !== null
                    ? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
                    : null;

                  return driverDto ? (
                    <div className="flex items-center gap-2">
                      <div className="flex-1">
                        <DriverIdentity
                          driver={driverDto}
                          href={`/drivers/${ownerMembership.driverId}?from=league-management&leagueId=${leagueId}`}
                          meta={meta}
                          size="sm"
                        />
                      </div>
                      <span className={`px-2 py-1 text-xs font-medium rounded border ${roleDisplay.badgeClasses}`}>
                        {roleDisplay.text}
                      </span>
                    </div>
                  ) : null;
                })()}

                {adminMemberships.slice(0, 3).map((membership) => {
                  const driverDto = driversById[membership.driverId];
                  const summary = buildDriverSummary(membership.driverId);
                  const roleDisplay = getLeagueRoleDisplay('admin');
                  const meta = summary && summary.rating !== null
                    ? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
                    : null;

                  return driverDto ? (
                    <div key={membership.driverId} className="flex items-center gap-2">
                      <div className="flex-1">
                        <DriverIdentity
                          driver={driverDto}
                          href={`/drivers/${membership.driverId}?from=league-management&leagueId=${leagueId}`}
                          meta={meta}
                          size="sm"
                        />
                      </div>
                      <span className={`px-2 py-1 text-xs font-medium rounded border ${roleDisplay.badgeClasses}`}>
                        {roleDisplay.text}
                      </span>
                    </div>
                  ) : null;
                })}

                {stewardMemberships.slice(0, 3).map((membership) => {
                  const driverDto = driversById[membership.driverId];
                  const summary = buildDriverSummary(membership.driverId);
                  const roleDisplay = getLeagueRoleDisplay('steward');
                  const meta = summary && summary.rating !== null
                    ? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
                    : null;

                  return driverDto ? (
                    <div key={membership.driverId} className="flex items-center gap-2">
                      <div className="flex-1">
                        <DriverIdentity
                          driver={driverDto}
                          href={`/drivers/${membership.driverId}?from=league-management&leagueId=${leagueId}`}
                          meta={meta}
                          size="sm"
                        />
                      </div>
                      <span className={`px-2 py-1 text-xs font-medium rounded border ${roleDisplay.badgeClasses}`}>
                        {roleDisplay.text}
                      </span>
                    </div>
                  ) : null;
                })}
              </div>
            </Card>
          )}
        </div>
      </div>
    </>
  );
}