'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { LeaguesTemplate } from '@/templates/LeaguesTemplate';
import { useServices } from '@/lib/services/ServiceProvider';
import type { LeagueSummaryViewModel } from '@/lib/view-models/LeagueSummaryViewModel';

export default function LeaguesInteractive() {
  const router = useRouter();
  const [realLeagues, setRealLeagues] = useState<LeagueSummaryViewModel[]>([]);
  const [loading, setLoading] = useState(true);

  const { leagueService } = useServices();

  const loadLeagues = useCallback(async () => {
    try {
      const leagues = await leagueService.getAllLeagues();
      setRealLeagues(leagues);
    } catch (error) {
      console.error('Failed to load leagues:', error);
    } finally {
      setLoading(false);
    }
  }, [leagueService]);

  useEffect(() => {
    void loadLeagues();
  }, [loadLeagues]);

  const handleLeagueClick = (leagueId: string) => {
    router.push(`/leagues/${leagueId}`);
  };

  const handleCreateLeagueClick = () => {
    router.push('/leagues/create');
  };

  return (
    <LeaguesTemplate
      leagues={realLeagues}
      loading={loading}
      onLeagueClick={handleLeagueClick}
      onCreateLeagueClick={handleCreateLeagueClick}
    />
  );
}