/**
 * Internal Dependencies
 */
import { navigate } from '@admin/router';
import { StepNav } from './components/StepNav';
import { WizardFooter } from './components/WizardFooter';
import { ExitDialog } from './components/ExitDialog';
import { StepWelcome } from './steps/StepWelcome';
import { StepModules } from './steps/StepModules';
import { StepAdSetup } from './steps/StepAdSetup';
import { StepVisibility } from './steps/StepVisibility';
import { StepDone } from './steps/StepDone';
import { useWizard } from './useWizard';

export function Wizard() {
	const {
		state,
		errors,
		publishing,
		subscribing,
		stepDefs,
		stepId,
		adStepIndex,
		set,
		toggleIn,
		goto,
		handleNext,
		handleSubscribe,
		nextLabel,
	} = useWizard();

	const content = {
		welcome: (
			<StepWelcome state={ state } set={ set } errors={ errors } />
		),
		modules: <StepModules />,
		ad: <StepAdSetup state={ state } set={ set } errors={ errors } />,
		visibility: (
			<>
				<StepVisibility
					state={ state }
					set={ set }
					toggleIn={ toggleIn }
				/>
				{ errors.publish && (
					<p className="mt-4 text-sm text-red-700">
						{ errors.publish }
					</p>
				) }
			</>
		),
		done: (
			<StepDone
				state={ state }
				set={ set }
				errors={ errors }
				subscribing={ subscribing }
				onSubscribe={ handleSubscribe }
				onEditPlacement={ () => goto( adStepIndex ) }
			/>
		),
	}[ stepId ];

	return (
		<div className="-mx-5 flex min-h-[calc(100vh-97px)] flex-col bg-bg-app">
			<StepNav
				steps={ stepDefs }
				step={ state.step }
				maxStep={ state.maxStep }
				onGoto={ goto }
			/>

			<div className="flex-1 px-8 pt-8 pb-12">
				<div className="mx-auto max-w-5xl">{ content }</div>
			</div>

			{ stepId !== 'done' && (
				<WizardFooter
					step={ state.step }
					totalSteps={ stepDefs.length }
					onBack={ () => state.step > 0 && goto( state.step - 1 ) }
					onSkip={ () => set( 'exitOpen', true ) }
					onNext={ handleNext }
					nextLabel={ nextLabel }
					nextDisabled={ publishing }
				/>
			) }

			{ state.exitOpen && (
				<ExitDialog
					onCancel={ () => set( 'exitOpen', false ) }
					onConfirm={ () => navigate( '/welcome' ) }
				/>
			) }
		</div>
	);
}
