import AsyncStorage from '@react-native-async-storage/async-storage';
import AnimatedScreen from 'components/AnimatedScreen';
import { useCallback, useEffect, useMemo, useState } from 'react';
import FirstStep from 'screens/welcome/FirstStep';
import SecondStep from 'screens/welcome/SecondStep';
import SelectLangPage from 'screens/welcome/SelectLangPage';
import ThirdStep from 'screens/welcome/ThirdStep';
import { changeLanguage } from 'utils/changeLanguage';

type OnboardingProps = {
  onFinish: () => void;
};

const Onboarding = ({ onFinish }: OnboardingProps) => {
  const [step, setStep] = useState(0);
  const [lang, setLang] = useState<'uz' | 'ru'>('uz');

  useEffect(() => {
    const loadLang = async () => {
      const savedLang = await AsyncStorage.getItem('selectedLanguage');
      if (savedLang === 'ru' || savedLang === 'uz') {
        setLang(savedLang);
        setStep(1);
      }
    };
    loadLang();
  }, []);

  const nextStep = useCallback(async () => {
    if (step < 3) {
      setStep(step + 1);
    } else {
      await AsyncStorage.setItem('hasSeenOnboarding', 'true');
      onFinish();
    }
  }, [step, onFinish]);

  const handleLanguageSelect = async (selectedLang: 'uz' | 'ru') => {
    await changeLanguage(selectedLang);
    setLang(selectedLang);
    setStep(1);
  };

  const stepComponents = useMemo(
    () => ({
      0: (
        <AnimatedScreen keyIndex={step}>
          <SelectLangPage onSelectLang={handleLanguageSelect} />
        </AnimatedScreen>
      ),
      1: (
        <AnimatedScreen keyIndex={step}>
          <FirstStep onNext={nextStep} lang={lang} />
        </AnimatedScreen>
      ),
      2: (
        <AnimatedScreen keyIndex={step}>
          <SecondStep onNext={nextStep} lang={lang} />
        </AnimatedScreen>
      ),
      3: (
        <AnimatedScreen keyIndex={step}>
          <ThirdStep onNext={nextStep} lang={lang} />
        </AnimatedScreen>
      ),
    }),
    [step, lang, nextStep],
  );

  return stepComponents[step as keyof typeof stepComponents];
};

export default Onboarding;
