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

import { Text } from '@/components/shared/Themed';
import styled from '@emotion/native';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '@/app/RootStackParamList';
import { loadUserSettings, saveUserSettings } from '@/components/shared/business/AsyncStorage';
import { Switch } from 'react-native';
import { VerticalSpacer } from '@/components/shared/Spacers';
import Button from '@/components/shared/Button';

type NavigationProp = NativeStackNavigationProp<RootStackParamList, 'Dashboard'>;

export default function Dashboard() {
  const navigation = useNavigation<NavigationProp>();
  const [soundEnabled, setSoundEnabled] = useState<boolean>(false);

  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>
      <Title>Preferences</Title>

      <Button label="Retour" onPress={() => navigation.navigate('Dashboard')} />

      <VerticalSpacer heightUnits={8} />

      <Row>
        <Text>Son activé ?</Text>

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

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

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

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

