'use client';

import React from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { CreateLeagueWizard } from './CreateLeagueWizard';
import { Section } from '@/ui/Section';
import { Container } from '@/ui/Container';
import { SearchParamParser } from '@/lib/routing/search-params/SearchParamParser';
import { SearchParamBuilder } from '@/lib/routing/search-params/SearchParamBuilder';

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

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

  const wizardParams = SearchParamParser.parseWizard(searchParams as unknown as URLSearchParams).unwrap();
  const rawStep = wizardParams.step;

  let currentStepName: StepName = 'basics';
  if (rawStep === 'basics' || 
      rawStep === 'visibility' || 
      rawStep === 'structure' || 
      rawStep === 'schedule' || 
      rawStep === 'scoring' || 
      rawStep === 'stewarding' || 
      rawStep === 'review') {
    currentStepName = rawStep;
  }

  const handleStepChange = (stepName: StepName) => {
    const builder = new SearchParamBuilder();
    // Copy existing params if needed, but here we just want to set the step
    if (searchParams) {
      searchParams.forEach((value, key) => {
        if (key !== 'step') builder.set(key, value);
      });
    }
    builder.step(stepName);
    router.push(`/leagues/create${builder.build()}`);
  };

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