import React, { useContext, useEffect, useState } from 'react';

import { Text } from '@/components/shared/Themed';
import styled from '@emotion/native';
import { loadUserSettings, saveUserSettings } from '@/components/shared/business/AsyncStorage';
import { Switch } from 'react-native';
import { i18n } from './i18n/i18n';
import { LanguageContext } from '@/app/shared/providers/LanguageProvider';
import DropDownPicker from "react-native-dropdown-picker";
import { VerticalSpacer } from '@/components/shared/Spacers';

const t = i18n.scoped('settings');

export default function Dashboard() {
  const [soundEnabled, setSoundEnabled] = useState<boolean>(false);
  const { userChangeLanguage } = useContext(LanguageContext)
  const [languageOpen, setLanguageOpen] = useState(false);
  const [languageValue, setLanguageValue] = useState(i18n.localI18n.locale);
  const [language, setLanguage] = useState([
    { label: t('french'), value: "fr" },
    { label: t('english'), value: "en" },
  ]);

  useEffect(() => {
    const init = async () => {
      try {
        const soundEnabledLocal = await loadUserSettings('soundEnabled');

        if (soundEnabledLocal === null) {
          setSoundEnabled(true);
        } else {
          setSoundEnabled(Boolean(Number(soundEnabledLocal)));
        }
      } catch (error) {
        throw new Error('Erreur lors du chargement des paramètres utilisateur');
      }
    };

    init();
  }, []);

  useEffect(() => {
    saveUserSettings('soundEnabled', String(Number(soundEnabled)));
  }, [soundEnabled]);

  return (
    <Container>
      <Row>
        <Text>{t('soundActivate')}</Text>

        <Switch
          onValueChange={() => setSoundEnabled(previousState => !previousState)}
          value={soundEnabled}
        />
      </Row>

      <VerticalSpacer heightUnits={5} />

      <Text>{t('language')}</Text>
      <VerticalSpacer heightUnits={2} />
      <Row>
        <DropDownPicker
          open={languageOpen}
          value={languageValue}
          items={language}
          setOpen={setLanguageOpen}
          setValue={setLanguageValue}
          setItems={setLanguage}
          placeholder={languageValue ?? ''}
          onChangeValue={(value: any) => {
            const formattedValue = value === 'fr' ? 'fr' : 'en'
            userChangeLanguage(formattedValue)
          }}
        />
      </Row>
    </Container>
  );
}

const Title = styled(Text)(({ theme }) => ({
  textAlign: 'center',
  fontSize: 40,
  fontWeight: 'bold',
  color: theme.colors.fixed.black
}));

const Row = styled.View({
  flexDirection: 'row',
  justifyContent: 'space-between',
  alignItems: 'center'
})

const Container = styled.View({
  padding: 20
})
