import { h } from 'preact';
import { Screen } from '../ui/Layout';
import { Player1Step, Player2Step, Player3Step, GameTypeStep, BreakRuleStep, BreakOrderStep, RaceToStep } from '../NewGame';
import type { NewGameStep, NewGameData } from '../../types/game';

interface NewGameScreenProps {
  step: NewGameStep;
  data: NewGameData;
  playerHistory: string[];
  onStepChange: (step: NewGameStep) => void;
  onDataChange: (data: Partial<NewGameData>) => void;
  onCreateGame: (data: NewGameData) => void;
  onCancel: () => void;
  onShowValidation: (message: string) => void;
}

export default function NewGameScreen({
  step,
  data,
  playerHistory,
  onStepChange,
  onDataChange,
  onCreateGame,
  onCancel,
  onShowValidation,
}: NewGameScreenProps) {
  const handlePlayer1Next = (name: string) => {
    onDataChange({ player1: name });
    onStepChange('player2');
  };

  const handlePlayer2Next = (name: string) => {
    onDataChange({ player2: name });
    onStepChange('player3');
  };

  const handlePlayer3Next = (name: string) => {
    onDataChange({ player3: name });
    onStepChange('gameType');
  };

  const handleGameTypeNext = (type: string) => {
    onDataChange({ 
      gameType: type as any, // Type assertion for now, could be improved with proper validation
      raceTo: '8'
    });
    onStepChange('raceTo');
  };

  const handleBreakRuleNext = (rule: 'winnerbreak' | 'wechselbreak') => {
    onDataChange({ breakRule: rule });
    try { localStorage.setItem('lastBreakRule', rule); } catch {}
    onStepChange('breakOrder');
  };

  const handleBreakOrderNext = (first: number, second?: number) => {
    const finalData = { ...data, breakFirst: first, breakSecond: second ?? '' } as any;
    onDataChange({ breakFirst: first, breakSecond: second ?? '' });
    try {
      localStorage.setItem('lastBreakFirst', String(first));
      if (second) localStorage.setItem('lastBreakSecond', String(second));
    } catch {}
    onCreateGame(finalData as any);
  };

  const handleRaceToNext = (raceTo: string) => {
    const finalData = { ...data, raceTo };
    // After race to, go to break rule selection
    onDataChange({ raceTo });
    onStepChange('breakRule');
  };

  const handleStepBack = () => {
    switch (step) {
      case 'player2':
        onStepChange('player1');
        break;
      case 'player3':
        onStepChange('player2');
        break;
      case 'gameType':
        onStepChange('player3');
        break;
      case 'raceTo':
        onStepChange('gameType');
        break;
      case 'breakRule':
        onStepChange('raceTo');
        break;
      case 'breakOrder':
        onStepChange('breakRule');
        break;
      default:
        onCancel();
    }
  };

  return (
    <Screen>
      {step === 'player1' && (
        <Player1Step
          playerNameHistory={playerHistory}
          onNext={handlePlayer1Next}
          onCancel={onCancel}
          initialValue={data.player1}
        />
      )}
      
      {step === 'player2' && (
        <Player2Step
          playerNameHistory={playerHistory}
          onNext={handlePlayer2Next}
          onCancel={handleStepBack}
          initialValue={data.player2}
        />
      )}
      
      {step === 'player3' && (
        <Player3Step
          playerNameHistory={playerHistory}
          onNext={handlePlayer3Next}
          onCancel={handleStepBack}
          initialValue={data.player3}
        />
      )}
      
      {step === 'gameType' && (
        <GameTypeStep
          onNext={handleGameTypeNext}
          onCancel={handleStepBack}
          initialValue={data.gameType}
        />
      )}

      
      
      {step === 'raceTo' && (
        <RaceToStep
          onNext={handleRaceToNext}
          onCancel={handleStepBack}
          initialValue={data.raceTo}
          gameType={data.gameType}
        />
      )}

      {step === 'breakRule' && (
        <BreakRuleStep
          onNext={handleBreakRuleNext}
          onCancel={handleStepBack}
          initialValue={(data.breakRule as any) || (typeof window !== 'undefined' ? (localStorage.getItem('lastBreakRule') as any) : 'winnerbreak') || 'winnerbreak'}
        />
      )}

      {step === 'breakOrder' && (
        <BreakOrderStep
          players={[data.player1, data.player2, data.player3]}
          rule={(data.breakRule as any) || 'winnerbreak'}
          onNext={handleBreakOrderNext}
          onCancel={handleStepBack}
          initialFirst={(typeof window !== 'undefined' && localStorage.getItem('lastBreakFirst')) ? parseInt(localStorage.getItem('lastBreakFirst')!, 10) : 1}
          initialSecond={(typeof window !== 'undefined' && localStorage.getItem('lastBreakSecond')) ? parseInt(localStorage.getItem('lastBreakSecond')!, 10) : undefined}
        />
      )}
    </Screen>
  );
}