'use client';

import React from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import CreateLeagueWizard from '@/components/leagues/CreateLeagueWizard';
import Section from '@/components/ui/Section';
import Container from '@/components/ui/Container';

type StepName = 'basics' | 'visibility' | 'structure' | 'schedule' | 'scoring' | 'stewarding' | 'review';

function normalizeStepName(raw: string | null): StepName {
  switch (raw) {
    case 'basics':
    case 'visibility':
    case 'structure':
    case 'schedule':
    case 'scoring':
    case 'stewarding':
    case 'review':
      return raw;
    default:
      return 'basics';
  }
}

export default function CreateLeaguePage() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const currentStepName = normalizeStepName(
    searchParams && typeof searchParams.get === 'function'
      ? searchParams.get('step')
      : null,
  );

  const handleStepChange = (stepName: StepName) => {
    const params = new URLSearchParams(
      searchParams && typeof searchParams.toString === 'function'
        ? searchParams.toString()
        : '',
    );
    params.set('step', stepName);
    const query = params.toString();
    const href = query ? `/leagues/create?${query}` : '/leagues/create';
    router.push(href);
  };

  return (
    <Section>
      <Container size="md">
        <CreateLeagueWizard stepName={currentStepName} onStepChange={handleStepChange} />
      </Container>
    </Section>
  );
}