import { View, Text, ScrollView } from "react-native";
import React, { useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Button } from "@rneui/themed";
import MyModal from "../../../components/MyModal";
import Toast from "react-native-toast-message";
import baseRequest from "../../../utils/baseRequest";
import { generateSignature } from "../../../utils/crypto";

export default function DeleteAccount({ navigation, route }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [deadline, setDeadline] = useState();

  const apiUrl = process.env.EXPO_PUBLIC_API_URL;

  //查询用户是否在注销中
  const checkAccountStatus = async () => {
    try {
      const base = await baseRequest();
      const signature = await generateSignature({
        ...base,
      });
      const _response = await fetch(
        `${apiUrl}/api/account_cancellation/list_by_mid?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
          }),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      if (_data.data.status === 0) setDeadline(_data.data.due_time);
    } catch (error) {
      console.error(error);
    }
  };
  useEffect(() => {
    checkAccountStatus();
  }, []);

  //提交注销申请
  const handleDeleteAccount = async () => {
    try {
      const base = await baseRequest();
      const signature = await generateSignature({
        ...base,
      });
      const _response = await fetch(
        `${apiUrl}/api/account/cancel?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
          }),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      checkAccountStatus();
      setIsModalVisible(false);
    } catch (error) {
      console.error(error);
    }
  };

  //取消注销
  const undoDeleteAccount = async () => {
    try {
      const base = await baseRequest();
      const signature = await generateSignature({
        ...base,
      });
      const _response = await fetch(
        `${apiUrl}/api/account/abort_cancellation?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
          }),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      setDeadline();
    } catch (error) {
      console.error(error);
    }
  };

  //格式化时间戳
  function formatDeadline(timestamp) {
    const date = new Date(timestamp * 1000); // 时间戳以秒为单位，需要乘以1000转换成毫秒
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    const hours = ("0" + date.getHours()).slice(-2);
    const minutes = ("0" + date.getMinutes()).slice(-2);
    const seconds = ("0" + date.getSeconds()).slice(-2);

    return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
  }

  return (
    <ScrollView
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("p-4 flex-1")}>
        <Text style={tailwind("text-white text-lg font-medium")}>
          注销必看须知:
        </Text>
        <View style={tailwind("bg-[#13121F] rounded-2xl p-2 mt-2")}>
          <Text style={tailwind("text-white text-base font-medium")}>
            1、账号个人信息
          </Text>
          <Text style={tailwind("text-[#FFFFFFB2] text-base")}>
            账号注销后，您将永远失去该账户的所有内容，且无法恢复。包括但不限于：个人资料信息、访问记录、关注列表、私信聊天记录等。
          </Text>
          <Text style={tailwind("text-white text-base font-medium mt-1")}>
            2、账号资产与权益
          </Text>
          <Text style={tailwind("text-[#FFFFFFB2] text-base")}>
            账号注销后，您将失去所有账号使用期间获得的资产与权益，且无法恢复。包括但不限于您的金币、钻石、会员特权以及其他已付费的订单商品等。
          </Text>
          <Text style={tailwind("text-white text-base font-medium mt-1")}>
            3、注销时间
          </Text>
          <Text style={tailwind("text-[#FFFFFFB2] text-base")}>
            您发起注销账户申请后，我们将在7个自然日后完全清除您的账号信息，在此期间您可以随时在本页面撤销该申请。
          </Text>
          <Text style={tailwind("text-white text-base font-medium mt-1")}>
            4、其他
          </Text>
          <Text style={tailwind("text-[#FFFFFFB2] text-base")}>
            平台入驻创作者请联系运营进行注销。
          </Text>
        </View>
        {deadline && (
          <Text style={tailwind("text-[#F53030] text-base font-medium mt-2")}>
            您的账号将于{formatDeadline(deadline)}
            注销，如需取消注销，请点击下方“取消注销”
          </Text>
        )}
        <Button
          color="#FF669E"
          radius="999"
          size="md"
          onPress={deadline ? undoDeleteAccount : () => setIsModalVisible(true)}
          titleStyle={tailwind("text-base")}
          containerStyle={tailwind("mt-16")}
        >
          {deadline ? "取消注销" : "确认注销账号"}
        </Button>
      </View>
      <MyModal
        visible={isModalVisible}
        setVisible={setIsModalVisible}
        title={"您确认要注销此账号吗？"}
        content={"注销后无法恢复，请仔细阅读《注销必看须知》后确认。"}
        confirm={handleDeleteAccount}
        confirmLeft
        highlightCancel
      />
    </ScrollView>
  );
}
