'use client';

import Breadcrumbs from '@/components/layout/Breadcrumbs';
import LeagueHeader from '@/components/leagues/LeagueHeader';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { useServices } from '@/lib/services/ServiceProvider';
import { LeaguePageDetailViewModel } from '@/lib/view-models/LeaguePageDetailViewModel';
import { useParams, usePathname, useRouter } from 'next/navigation';
import React, { useEffect, useState } from 'react';

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 { leagueService } = useServices();

  const [leagueDetail, setLeagueDetail] = useState<LeaguePageDetailViewModel | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadLeague() {
      try {
        const leagueDetailData = await leagueService.getLeagueDetail(leagueId, currentDriverId);

        setLeagueDetail(leagueDetailData);
      } catch (error) {
        console.error('Failed to load league:', error);
      } finally {
        setLoading(false);
      }
    }

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

  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 (!leagueDetail) {
    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: 'Schedule Admin', href: `/leagues/${leagueId}/schedule/admin`, exact: false },
    { 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 = leagueDetail.isAdmin ? [...baseTabs, ...adminTabs] : baseTabs;


  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: leagueDetail.name },
          ]}
        />

        <LeagueHeader
          leagueId={leagueDetail.id}
          leagueName={leagueDetail.name}
          description={leagueDetail.description}
          ownerId={leagueDetail.ownerId}
          ownerName={leagueDetail.ownerName}
          mainSponsor={leagueDetail.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>
  );
}