import { useEffect, useState } from "react";
import { Button, StyleSheet, Text, View } from "react-native";

import * as Settings from "expo-settings";

export default function App() {
  const [theme, setTheme] = useState<Settings.Theme>(Settings.getTheme());

  useEffect(() => {
    const subscription = Settings.addThemeListener(({ theme: newTheme }) => {
      console.log({ newTheme });
      console.log({ theme });
      setTheme(newTheme);
    });

    return () => subscription.remove();
  }, [setTheme]);

  return (
    <View style={styles.container}>
      <Text>Preferred theme: {theme}</Text>
      <Button
        title="Toggle theme"
        onPress={() => {
          console.log({toggleTheme: toggleTheme(theme)});
          Settings.setTheme(toggleTheme(theme));
        }}
      />
    </View>
  );
}

function toggleTheme(theme: Settings.Theme) {
  if (theme === Settings.Theme.Light) {
    return Settings.Theme.Dark;
  } else if (theme === Settings.Theme.Dark) {
    return Settings.Theme.System;
  } else {
    return Settings.Theme.Light;
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});
