'use client';

import React, { useState, useEffect } from 'react';
import { useParams, usePathname, useRouter } from 'next/navigation';
import Breadcrumbs from '@/components/layout/Breadcrumbs';
import LeagueHeader from '@/components/leagues/LeagueHeader';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import { isLeagueAdminOrHigherRole } from '@/lib/leagueRoles';
import type { League } from '@core/racing/domain/entities/League';

// Main sponsor info for "by XYZ" display
interface MainSponsorInfo {
  name: string;
  logoUrl: string;
  websiteUrl: string;
}

export default function LeagueLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const params = useParams();
  const pathname = usePathname();
  const router = useRouter();
  const leagueId = params.id as string;
  const currentDriverId = useEffectiveDriverId();
  
  const [league, setLeague] = useState<League | null>(null);
  const [ownerName, setOwnerName] = useState<string>('');
  const [mainSponsor, setMainSponsor] = useState<MainSponsorInfo | null>(null);
  const [isAdmin, setIsAdmin] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadLeague() {
      try {
        const leagueRepo = getLeagueRepository();
        const driverRepo = getDriverRepository();
        const membershipRepo = getLeagueMembershipRepository();
        const seasonRepo = getSeasonRepository();
        const sponsorRepo = getSponsorRepository();
        const sponsorshipRepo = getSeasonSponsorshipRepository();
        
        const leagueData = await leagueRepo.findById(leagueId);
        
        if (!leagueData) {
          setLoading(false);
          return;
        }

        setLeague(leagueData);

        const owner = await driverRepo.findById(leagueData.ownerId);
        setOwnerName(owner ? owner.name : `${leagueData.ownerId.slice(0, 8)}...`);

        // Check if current user is admin
        const membership = await membershipRepo.getMembership(leagueId, currentDriverId);
        setIsAdmin(membership ? isLeagueAdminOrHigherRole(membership.role) : false);

        // Load main sponsor for "by XYZ" display
        try {
          const seasons = await seasonRepo.findByLeagueId(leagueId);
          const activeSeason = seasons.find((s: { status: string }) => s.status === 'active') ?? seasons[0];
          
          if (activeSeason) {
            const sponsorships = await sponsorshipRepo.findBySeasonId(activeSeason.id);
            const mainSponsorship = sponsorships.find(s => s.tier === 'main' && s.status === 'active');
            
            if (mainSponsorship) {
              const sponsor = await sponsorRepo.findById(mainSponsorship.sponsorId);
              if (sponsor) {
                setMainSponsor({
                  name: sponsor.name,
                  logoUrl: sponsor.logoUrl ?? '',
                  websiteUrl: sponsor.websiteUrl ?? '',
                });
              }
            }
          }
        } catch (sponsorError) {
          console.warn('Failed to load main sponsor:', sponsorError);
        }
      } catch (error) {
        console.error('Failed to load league:', error);
      } finally {
        setLoading(false);
      }
    }

    loadLeague();
  }, [leagueId, currentDriverId]);

  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 (!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">
          <div className="text-center text-gray-400">League not found</div>
        </div>
      </div>
    );
  }

  // Define tab configuration
  const baseTabs = [
    { label: 'Overview', href: `/leagues/${leagueId}`, exact: true },
    { label: 'Schedule', href: `/leagues/${leagueId}/schedule`, exact: false },
    { label: 'Standings', href: `/leagues/${leagueId}/standings`, exact: false },
    { label: 'Rulebook', href: `/leagues/${leagueId}/rulebook`, exact: false },
  ];

  const adminTabs = [
    { label: 'Sponsorships', href: `/leagues/${leagueId}/sponsorships`, exact: false },
    { label: 'Stewarding', href: `/leagues/${leagueId}/stewarding`, exact: false },
    { label: 'Wallet', href: `/leagues/${leagueId}/wallet`, exact: false },
    { label: 'Settings', href: `/leagues/${leagueId}/settings`, exact: false },
  ];

  const tabs = isAdmin ? [...baseTabs, ...adminTabs] : baseTabs;

  // Determine active tab
  const activeTab = tabs.find(tab =>
    tab.exact ? pathname === tab.href : pathname.startsWith(tab.href)
  );

  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">
        <Breadcrumbs
          items={[
            { label: 'Home', href: '/' },
            { label: 'Leagues', href: '/leagues' },
            { label: league.name },
          ]}
        />

        <LeagueHeader
          leagueId={league.id}
          leagueName={league.name}
          description={league.description}
          ownerId={league.ownerId}
          ownerName={ownerName}
          mainSponsor={mainSponsor}
        />

        {/* Tab Navigation */}
        <div className="mb-6 border-b border-charcoal-outline">
          <div className="flex gap-6 overflow-x-auto">
            {tabs.map((tab) => (
              <button
                key={tab.href}
                onClick={() => router.push(tab.href)}
                className={`pb-3 px-1 font-medium whitespace-nowrap transition-colors ${
                  (tab.exact ? pathname === tab.href : pathname.startsWith(tab.href))
                    ? 'text-primary-blue border-b-2 border-primary-blue'
                    : 'text-gray-400 hover:text-white'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>

        <div>{children}</div>
      </div>
    </div>
  );
}