'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 { getLeagueRepository, getDriverRepository, getLeagueMembershipRepository } from '@/lib/di-container';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import { isLeagueAdminOrHigherRole } from '@/lib/leagueRoles';
import type { League } from '@gridpilot/racing/domain/entities/League';

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 [isAdmin, setIsAdmin] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadLeague() {
      try {
        const leagueRepo = getLeagueRepository();
        const driverRepo = getDriverRepository();
        const membershipRepo = getLeagueMembershipRepository();
        
        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);
      } 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: 'Stewarding', href: `/leagues/${leagueId}/stewarding`, 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}
        />

        {/* 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>
  );
}