import { View, Text, TouchableOpacity } from "react-native";
import React, { useState, useEffect, useCallback } from "react";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useTailwind } from "tailwind-rn";
import { Image } from "expo-image";
import { Divider, Icon } from "@rneui/themed";
import MediaPickerModal from "../../../components/MediaPickerModal";
import { get, save } from "../../../utils/storeInfo";
import { useFocusEffect } from "@react-navigation/native";
import { uploadImage } from "../../../utils/upload";
import baseRequest from "../../../utils/baseRequest";
import Toast from "react-native-toast-message";
import { generateSignature } from "../../../utils/crypto";

const blurhash = "LcKUTa%gOYWBYRt6xuoJo~s8V@fk";

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

  //选取头像
  const [head, setHead] = useState([]);
  const [mediaPickerModalVisible, setMediaPickerModalVisible] = useState(false);

  //获取页面数据
  const [data, setData] = useState({});
  useFocusEffect(
    useCallback(() => {
      async function getData() {
        try {
          const account = await get("account");
          if (account) {
            setData(account);
          }
        } catch (e) {
          console.warn(e);
        }
      }
      getData();
    }, [])
  );

  //头像变化时上传到oss
  useEffect(() => {
    if (head.length === 0) return;
    const uploadHead = async () => {
      const avatarId = await uploadImage(head[0]);
      //获取环境变量
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;

      const base = await baseRequest();
      const account = await get("account");
      const signature = await generateSignature({
        ...base,
        mid: account.mid,
        avatar: { image_ids: [avatarId] },
      });
      try {
        const response = await fetch(
          `${apiUrl}/api/account/update?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              ...base,
              mid: account.mid,
              avatar: { image_ids: [avatarId] },
            }),
          }
        );
        const temData = await response.json();
        if (temData.ret === -1) {
          Toast.show({
            type: "error",
            text1: temData.msg,
            topOffset: 60,
          });
          return;
        }
        //向服务器请求新的账号信息并保存到本地
        const signature2 = await generateSignature({
          ...base,
          mid: account.mid,
        });
        const accountResponse = await fetch(
          `${apiUrl}/api/account/list_by_mid?signature=${signature2}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              ...base,
              mid: account.mid,
            }),
          }
        );
        const accountData = await accountResponse.json();
        if (accountData.ret === -1) {
          Toast.show({
            type: "error",
            text1: accountData.msg,
            topOffset: 60,
          });
          return;
        }
        await save("account", accountData.data.account);
        setData(accountData.data.account);
      } catch (error) {
        console.error(error);
      }
    };
    uploadHead();
  }, [head]);

  return (
    <View
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <MediaPickerModal
        visible={mediaPickerModalVisible}
        setVisible={setMediaPickerModalVisible}
        type="image"
        maxCount={1}
        setAssets={setHead}
      />
      <View style={tailwind("px-4")}>
        <View style={tailwind("flex-row justify-between items-center mt-2")}>
          <Text style={tailwind("text-base text-white font-medium")}>头像</Text>
          <TouchableOpacity
            onPress={() => setMediaPickerModalVisible(true)}
            style={tailwind("flex-row items-center")}
          >
            <Image
              style={tailwind("w-12 h-12 rounded-full")}
              source={data?.avatar?.images[0]?.urls[0]}
              placeholder={blurhash}
              contentFit="cover"
              transition={1000}
              cachePolicy="disk"
            />
            <Icon name="chevron-forward-outline" type="ionicon" color="white" />
          </TouchableOpacity>
        </View>
        <Divider style={tailwind("my-2")} />
        <View style={tailwind("flex-row justify-between items-center mt-2")}>
          <Text style={tailwind("text-base text-white font-medium")}>昵称</Text>
          <TouchableOpacity
            onPress={() => navigation.navigate("EditUserName")}
            style={tailwind("flex-row items-center")}
          >
            <Text style={tailwind("text-base text-white font-medium")}>
              {data?.name}
            </Text>
            <Icon name="chevron-forward-outline" type="ionicon" color="white" />
          </TouchableOpacity>
        </View>
        <Divider style={tailwind("my-2")} />
        <View style={tailwind("flex-row justify-between items-center mt-2")}>
          <Text style={tailwind("text-base text-white font-medium")}>ID</Text>
          <View style={tailwind("flex-row items-center")}>
            <Text style={tailwind("text-base text-[#FFFFFF80] font-medium")}>
              {data?.user_id}
            </Text>
          </View>
        </View>
        <Divider style={tailwind("my-2")} />
      </View>
    </View>
  );
}
