'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 FeatureLimitationTooltip from '@/components/alpha/FeatureLimitationTooltip';
import { League } from '@/domain/entities/League';
import { Race } from '@/domain/entities/Race';
import { Driver } from '@/domain/entities/Driver';
import { getLeagueRepository, getRaceRepository, getDriverRepository } from '@/lib/di-container';

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 [races, setRaces] = useState<Race[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  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 races for this league
      const allRaces = await raceRepo.findAll();
      const leagueRaces = allRaces
        .filter(race => race.leagueId === leagueId)
        .sort((a, b) => new Date(a.scheduledAt).getTime() - new Date(b.scheduledAt).getTime());
      
      setRaces(leagueRaces);
    } 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="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-6xl mx-auto">
          <div className="text-center text-gray-400">Loading league...</div>
        </div>
      </div>
    );
  }

  if (error || !league) {
    return (
      <div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-6xl mx-auto">
          <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>
        </div>
      </div>
    );
  }

  const upcomingRaces = races.filter(race => race.status === 'scheduled');

  return (
    <div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-6xl mx-auto">
        {/* Breadcrumb */}
        <div className="mb-6">
          <button
            onClick={() => router.push('/leagues')}
            className="text-gray-400 hover:text-primary-blue transition-colors text-sm flex items-center gap-2"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            Back to Leagues
          </button>
        </div>

        {/* League Header */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-2">
            <h1 className="text-3xl font-bold text-white">{league.name}</h1>
            <FeatureLimitationTooltip message="Multi-league memberships coming in production">
              <span className="px-2 py-1 text-xs font-medium bg-primary-blue/10 text-primary-blue rounded border border-primary-blue/30">
                Alpha: Single League
              </span>
            </FeatureLimitationTooltip>
          </div>
          <p className="text-gray-400">{league.description}</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
          {/* 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">
              <Button
                variant="primary"
                className="w-full"
                onClick={() => router.push(`/races?leagueId=${leagueId}`)}
              >
                Schedule Race
              </Button>

              <Button
                variant="secondary"
                className="w-full"
                onClick={() => router.push(`/leagues/${leagueId}/standings`)}
              >
                View Standings
              </Button>
            </div>
          </Card>
        </div>

        {/* Upcoming Races */}
        <Card>
          <h2 className="text-xl font-semibold text-white mb-4">Upcoming Races</h2>
          
          {upcomingRaces.length === 0 ? (
            <div className="text-center py-8 text-gray-400">
              <p className="mb-2">No upcoming races scheduled</p>
              <p className="text-sm text-gray-500">Click &ldquo;Schedule Race&rdquo; to create your first race</p>
            </div>
          ) : (
            <div className="space-y-3">
              {upcomingRaces.map((race) => (
                <div
                  key={race.id}
                  className="p-4 rounded-lg bg-deep-graphite border border-charcoal-outline hover:border-primary-blue transition-all duration-200 cursor-pointer hover:scale-[1.02]"
                  onClick={() => router.push(`/races/${race.id}`)}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="text-white font-medium">{race.track}</h3>
                      <p className="text-sm text-gray-400">{race.car}</p>
                      <p className="text-xs text-gray-500 mt-1 uppercase">{race.sessionType}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-white text-sm">
                        {new Date(race.scheduledAt).toLocaleDateString()}
                      </p>
                      <p className="text-xs text-gray-500">
                        {new Date(race.scheduledAt).toLocaleTimeString([], {
                          hour: '2-digit',
                          minute: '2-digit'
                        })}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}