import { h } from 'preact';
import { useEffect, useState } from 'preact/hooks';
import styles from '../NewGame.module.css';
import type { BreakRule } from '@lib/domain/types';
import { WizardNav } from '../components/WizardNav';
import { WizardStepForm } from '../components/WizardStepForm';

interface BreakOrderStepProps {
  players: string[];
  rule: BreakRule;
  onNext: (first: number, second?: number) => void;
  onCancel: () => void;
  initialFirst?: number;
  initialSecond?: number;
}

export const BreakOrderStep = ({ players, rule, onNext, onCancel, initialFirst = 1, initialSecond }: BreakOrderStepProps) => {
  const playerCount = players.filter(Boolean).length;
  const [first, setFirst] = useState<number>(initialFirst);
  const [second, setSecond] = useState<number | undefined>(initialSecond);

  useEffect(() => {
    if (!initialSecond && rule === 'wechselbreak' && playerCount === 3) {
      setSecond(2);
    }
  }, [initialSecond, rule, playerCount]);

  const handleFirst = (idx: number) => {
    setFirst(idx);
    const isImmediateFlow = rule !== 'wechselbreak' || playerCount !== 3;
    if (isImmediateFlow) {
      onNext(idx);
    }
  };

  const handleSecond = (idx: number) => {
    setSecond(idx);
    if (rule === 'wechselbreak' && playerCount === 3 && first > 0) {
      onNext(first, idx);
    }
  };

  const handleSubmit = (e: Event) => {
    e.preventDefault();

    if (rule === 'wechselbreak' && playerCount === 3) {
      if (first > 0 && (second ?? 0) > 0) {
        onNext(first, second);
      }
      return;
    }

    if (first > 0) {
      onNext(first);
    }
  };

  return (
    <WizardStepForm
      ariaLabel="Break-Reihenfolge wählen"
      title="Wer hat den ersten Anstoss?"
      currentStep={7}
      onSubmit={handleSubmit}
      footer={
        <WizardNav
          onBack={onCancel}
          nextDisabled={
            (rule === 'wechselbreak' && playerCount === 3) ? !(first > 0 && (second ?? 0) > 0) : !(first > 0)
          }
        />
      }
    >
        <div className={styles['choice-heading']}>Wer hat den ersten Anstoss?</div>
        <div className={styles['quick-picks-row']}>
          {players.filter(Boolean).map((name, idx) => (
            <button
              key={`first-${idx}`}
              type="button"
              className={`${styles['quick-pick-btn']} ${first === (idx + 1) ? styles['selected'] : ''}`}
              onClick={() => handleFirst(idx + 1)}
              aria-label={`Zuerst: ${name}`}
              style={{ minWidth: 160, minHeight: 64 }}
            >
              {name}
            </button>
          ))}
        </div>

        {rule === 'wechselbreak' && playerCount === 3 && (
          <>
            <div className={styles['choice-heading']}>Wer hat den zweiten Anstoss?</div>
            <div className={styles['quick-picks-row']}>
              {players.filter(Boolean).map((name, idx) => (
                <button
                  key={`second-${idx}`}
                  type="button"
                  className={`${styles['quick-pick-btn']} ${second === (idx + 1) ? styles['selected'] : ''}`}
                  onClick={() => handleSecond(idx + 1)}
                  aria-label={`Zweites Break: ${name}`}
                  style={{ minWidth: 160, minHeight: 64 }}
                >
                  {name}
                </button>
              ))}
            </div>
          </>
        )}
    </WizardStepForm>
  );
};


