import { View, Text, ScrollView, TouchableOpacity } from "react-native";
import React, { useState, useEffect, useContext } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Icon, Button } from "@rneui/themed";
import * as FileSystem from "expo-file-system";
import { AuthContext } from "../../../App";
import MyDivider from "../../../components/MyDivider";

export default function SelectSettingItem({ navigation }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  //点击退出登陆
  const { signOut } = useContext(AuthContext);

  const [cacheSize, setCacheSize] = useState();
  //查看所有缓存文件大小
  useEffect(() => {
    async function getCacheDirectoryInfo() {
      const cacheInfo = await FileSystem.getInfoAsync(
        FileSystem.cacheDirectory
      );
      setCacheSize(cacheInfo.size);
    }
    getCacheDirectoryInfo();
  }, []);

  //清除所有图片缓存
  async function clearCache() {
    const cacheDir = FileSystem.cacheDirectory;
    const contents = await FileSystem.readDirectoryAsync(cacheDir);
    for (let file of contents) {
      await FileSystem.deleteAsync(`${cacheDir}/${file}`);
    }
    const cacheInfo = await FileSystem.getInfoAsync(cacheDir);
    setCacheSize(cacheInfo.size);
  }

  //可进详情的选项组件
  const SettingItem = ({ title, to }) => {
    return (
      <>
        <TouchableOpacity
          onPress={() => navigation.navigate(to)}
          style={tailwind("flex-row justify-between pt-4 pb-2")}
        >
          <Text style={tailwind("text-base text-white")}>{title}</Text>
          <Icon name="chevron-forward-outline" type="ionicon" color="white" />
        </TouchableOpacity>
        <MyDivider />
      </>
    );
  };
  return (
    <View
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <ScrollView style={tailwind("px-4 flex-1")}>
        <SettingItem title="黑名单" to="BannedList" />
        <SettingItem title="修改密码" to="EditPassword" />
        <SettingItem title="意见反馈" to="Feedback" />
        <TouchableOpacity
          onPress={clearCache}
          style={tailwind("flex-row justify-between pt-4 pb-2")}
        >
          <Text style={tailwind("text-base text-white")}>清理缓存</Text>
          <Text style={tailwind("text-base text-white")}>
            {`${(cacheSize / 1024 / 1024).toFixed(2)}M`}
          </Text>
        </TouchableOpacity>
        <MyDivider />
        <SettingItem title="关于我们" to="AboutUs" />
        <Button
          color="#FF669E"
          radius="999"
          size="md"
          onPress={signOut}
          titleStyle={tailwind("text-base")}
          containerStyle={{
            marginBottom: insets.bottom + 60,
            ...tailwind("mt-16"),
          }}
        >
          退出登录
        </Button>
      </ScrollView>
    </View>
  );
}
