'use client';

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { RaceStewardingTemplate, StewardingTab } from '@/templates/RaceStewardingTemplate';
import { useRaceStewardingData } from '@/hooks/useRaceStewardingService';
import { useLeagueMembership } from '@/hooks/useLeagueMembershipService';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';

export function RaceStewardingInteractive() {
  const router = useRouter();
  const params = useParams();
  const raceId = params.id as string;
  const currentDriverId = useEffectiveDriverId();

  // Fetch data
  const { data: stewardingData, isLoading, error } = useRaceStewardingData(raceId, currentDriverId);
  const { data: membership } = useLeagueMembership(stewardingData?.league?.id || '', currentDriverId);

  // UI State
  const [activeTab, setActiveTab] = useState<StewardingTab>('pending');

  const isAdmin = membership ? LeagueRoleUtility.isLeagueAdminOrHigherRole(membership.role) : false;

  // Actions
  const handleBack = () => {
    router.push(`/races/${raceId}`);
  };

  const handleReviewProtest = (protestId: string) => {
    // Navigate to protest review page
    router.push(`/leagues/${stewardingData?.league?.id}/stewarding/protests/${protestId}`);
  };

  // Transform data for template
  const templateData = stewardingData ? {
    race: stewardingData.race,
    league: stewardingData.league,
    pendingProtests: stewardingData.pendingProtests,
    resolvedProtests: stewardingData.resolvedProtests,
    penalties: stewardingData.penalties,
    driverMap: stewardingData.driverMap,
    pendingCount: stewardingData.pendingCount,
    resolvedCount: stewardingData.resolvedCount,
    penaltiesCount: stewardingData.penaltiesCount,
  } : undefined;

  return (
    <RaceStewardingTemplate
      stewardingData={templateData}
      isLoading={isLoading}
      error={error}
      onBack={handleBack}
      onReviewProtest={handleReviewProtest}
      isAdmin={isAdmin}
      activeTab={activeTab}
      setActiveTab={setActiveTab}
    />
  );
}