import { useState } from 'react';
import { useRouter } from 'expo-router';
import { OnboardingLayout } from '@/components/onboarding/OnboardingLayout';
import { NameInputStep } from '@/components/onboarding/NameInputStep';
import { IntentSelectionStep } from '@/components/onboarding/IntentSelectionStep';
import { setOnboardingCompleted, setUserProfile } from '@/src/storage/appStorage';

export default function OnboardingScreen() {
  const router = useRouter();
  const [step, setStep] = useState(0);
  const [name, setName] = useState('');
  const [intents, setIntents] = useState<string[]>([]);

  async function onFinish() {
    // Save whatever input we have
    await setUserProfile({ name, intents });
    await setOnboardingCompleted(true);
    router.replace('/(onboarding)/push-prompt');
  }

  async function onNext() {
    if (step === 0) {
      setStep(1);
    } else {
      await onFinish();
    }
  }

  async function onSkip() {
    // Skip logic: move to next step regardless of input
    if (step === 0) {
      setStep(1);
    } else {
      await onFinish();
    }
  }

  // Step 0: Next button requires input
  // Step 1: Next button always enabled (can proceed with empty selection)
  const nextEnabled = step === 0 ? name.trim().length > 0 : true;

  return (
    <OnboardingLayout
      onSkip={onSkip}
      onNext={onNext}
      nextEnabled={nextEnabled}
    >
      {step === 0 ? (
        <NameInputStep
          value={name}
          onChangeText={setName}
          onSubmitEditing={name.trim().length > 0 ? onNext : undefined}
        />
      ) : (
        <IntentSelectionStep
          selectedIds={intents}
          onToggle={(id) => {
            setIntents(prev =>
              prev.includes(id)
                ? prev.filter(i => i !== id)
                : [...prev, id]
            );
          }}
        />
      )}
    </OnboardingLayout>
  );
}
