'use client';

import { useRouter } from 'next/navigation';
import LeaderboardsTemplate from '@/templates/LeaderboardsTemplate';
import type { DriverLeaderboardItemViewModel } from '@/lib/view-models/DriverLeaderboardItemViewModel';
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';

// Shared state components
import { StateContainer } from '@/components/shared/state/StateContainer';
import { useDriverLeaderboard } from '@/hooks/driver/useDriverLeaderboard';
import { useAllTeams } from '@/hooks/team/useAllTeams';
import { Trophy } from 'lucide-react';

export default function LeaderboardsStatic() {
  const router = useRouter();

  const { data: driverData, isLoading: driversLoading, error: driversError, retry: driversRetry } = useDriverLeaderboard();
  const { data: teams, isLoading: teamsLoading, error: teamsError, retry: teamsRetry } = useAllTeams();

  const handleDriverClick = (driverId: string) => {
    router.push(`/drivers/${driverId}`);
  };

  const handleTeamClick = (teamId: string) => {
    router.push(`/teams/${teamId}`);
  };

  const handleNavigateToDrivers = () => {
    router.push('/leaderboards/drivers');
  };

  const handleNavigateToTeams = () => {
    router.push('/teams/leaderboard');
  };

  // Combine loading states
  const isLoading = driversLoading || teamsLoading;
  // Combine errors (prioritize drivers error)
  const error = driversError || teamsError;
  // Combine retry functions
  const retry = async () => {
    if (driversError) await driversRetry();
    if (teamsError) await teamsRetry();
  };

  // Prepare data for template
  const drivers = driverData?.drivers || [];
  const teamsData = teams || [];
  const hasData = drivers.length > 0 || teamsData.length > 0;

  return (
    <StateContainer
      data={hasData ? { drivers, teams: teamsData } : null}
      isLoading={isLoading}
      error={error}
      retry={retry}
      config={{
        loading: { variant: 'spinner', message: 'Loading leaderboards...' },
        error: { variant: 'full-screen' },
        empty: {
          icon: Trophy,
          title: 'No leaderboard data',
          description: 'There is no leaderboard data available at the moment.',
        }
      }}
      isEmpty={(data) => !data || (data.drivers.length === 0 && data.teams.length === 0)}
    >
      {(data) => (
        <LeaderboardsTemplate
          drivers={data.drivers}
          teams={data.teams}
          onDriverClick={handleDriverClick}
          onTeamClick={handleTeamClick}
          onNavigateToDrivers={handleNavigateToDrivers}
          onNavigateToTeams={handleNavigateToTeams}
        />
      )}
    </StateContainer>
  );
}