'use client';

import { useState, useEffect } 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 LeagueMembers from '@/components/leagues/LeagueMembers';
import LeagueSchedule from '@/components/leagues/LeagueSchedule';
import LeagueAdmin from '@/components/leagues/LeagueAdmin';
import StandingsTable from '@/components/leagues/StandingsTable';
import { League } from '@gridpilot/racing/domain/entities/League';
import { Standing } from '@gridpilot/racing/domain/entities/Standing';
import { Driver } from '@gridpilot/racing/domain/entities/Driver';
import { getLeagueRepository, getRaceRepository, getDriverRepository, getStandingRepository } from '@/lib/di-container';
import { getMembership, isOwnerOrAdmin, getCurrentDriverId } from '@/lib/racingLegacyFacade';

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<Standing[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'overview' | 'schedule' | 'standings' | 'members' | 'admin'>('overview');
  const [refreshKey, setRefreshKey] = useState(0);

  const currentDriverId = getCurrentDriverId();
  const membership = getMembership(leagueId, currentDriverId);
  const isAdmin = isOwnerOrAdmin(leagueId, currentDriverId);

  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
      const standingRepo = getStandingRepository();
      const allStandings = await standingRepo.findAll();
      const leagueStandings = allStandings.filter(s => s.leagueId === leagueId);
      setStandings(leagueStandings);

      // Load all drivers for standings
      const allDrivers = await driverRepo.findAll();
      setDrivers(allDrivers);
    } 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]);

  if (loading) {
    return (
      <div className="text-center text-gray-400">Loading league...</div>
    );
  }

  if (error || !league) {
    return (
      <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>
    );
  }

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

  return (
    <>
      {/* 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('members')}
            className={`px-3 py-1 text-xs font-medium rounded-full transition-colors ${
              activeTab === 'members'
                ? 'bg-primary-blue text-white'
                : 'text-gray-300 hover:text-white hover:bg-charcoal-outline/80'
            }`}
          >
            Members
          </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">Owner</label>
                <p className="text-white">{owner ? owner.name : `ID: ${league.ownerId.slice(0, 8)}...`}</p>
              </div>

              <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">League Settings</h3>
                
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm text-gray-500">Points System</label>
                    <p className="text-white">{league.settings.pointsSystem.toUpperCase()}</p>
                  </div>

                  <div>
                    <label className="text-sm text-gray-500">Session Duration</label>
                    <p className="text-white">{league.settings.sessionDuration} minutes</p>
                  </div>

                  <div>
                    <label className="text-sm text-gray-500">Qualifying Format</label>
                    <p className="text-white capitalize">{league.settings.qualifyingFormat}</p>
                  </div>
                </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 === 'members' && (
        <Card>
          <h2 className="text-xl font-semibold text-white mb-4">League Members</h2>
          <LeagueMembers leagueId={leagueId} key={refreshKey} />
        </Card>
      )}

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