import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  Image as NativeImage,
} from "react-native";
import React, { useCallback, useState, useEffect } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import MyDivider from "../../../components/MyDivider";
import { Icon } from "@rneui/themed";
import { Image } from "expo-image";
import MyModal from "../../../components/MyModal";
import baseRequest from "../../../utils/baseRequest";
import { generateSignature } from "../../../utils/crypto";
import Toast from "react-native-toast-message";

export default function SelectSpaceSettingItem({ navigation, route, data }) {
  const blurhash = "LcKUTa%gOYWBYRt6xuoJo~s8V@fk";

  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  //是否对主播展示代运营设置
  const [isAgencyHided, setIsAgencyHided] = useState(true);
  useEffect(() => {
    const getData = async () => {
      try {
        const apiUrl = process.env.EXPO_PUBLIC_API_URL;
        const base = await baseRequest();
        const body = {
          zid: data?.id,
          ...base,
        };
        const signature = await generateSignature(body);
        const _response = await fetch(
          `${apiUrl}/api/zone_third_partner/list?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(body),
          }
        );
        const _data = await _response.json();
        if (_data.ret === -1) {
          Toast.show({
            type: "error",
            text1: _data.msg,
            topOffset: 60,
          });
          return;
        }
        setIsAgencyHided(
          _data.data.zone_third_partner?.is_hided === 1 ? true : false
        );
      } catch (error) {
        console.error(error);
      }
    };
    getData();
  }, []);

  //可进详情的选项组件
  const SettingItem = useCallback(({ title, to }) => {
    return (
      <>
        <TouchableOpacity
          onPress={() => navigation.navigate(to, { data: data })}
          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 />
      </>
    );
  }, []);

  //格式化时间
  const formatDate = useCallback((timestamp) => {
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份从0开始,所以需要加1
    const day = date.getDate();
    return `${year}/${month}/${day}`;
  }, []);

  //退出空间
  const [isExitSpaceModalVisible, setIsExitSpaceModalVisible] = useState(false);
  const handleExitSpace = async () => {
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const body = {
        zid: data?.id,
        ...base,
      };
      const signature = await generateSignature(body);
      const _response = await fetch(
        `${apiUrl}/api/zone/exit?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      Toast.show({
        type: "success",
        text1: "退出空间成功",
        topOffset: 60,
      });
      setTimeout(() => navigation.replace("HomeTab"), 500);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <View
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <ScrollView style={tailwind("p-4 flex-1")}>
        <TouchableOpacity
          activeOpacity={1}
          onPress={
            data?.visitor_role === 3
              ? () => navigation.navigate("SpaceIntroSetting", { data: data })
              : null
          }
          style={tailwind("flex flex-row items-center mb-2")}
        >
          <Image
            source={data?.streamer_ext?.avatar?.images[0]?.urls[0]}
            contentFit="cover"
            transition={1000}
            placeholder={blurhash}
            cachePolicy="disk"
            style={{
              aspectRatio: "1/1",
              ...tailwind("w-[4.6rem] h-[4.6rem] rounded-full"),
            }}
          />
          <View style={tailwind("flex flex-col flex-1 mx-2 justify-between")}>
            <Text
              style={{
                fontSize: 22,
                ...tailwind("text-white font-medium"),
              }}
              numberOfLines={1}
              ellipsizeMode="tail"
            >
              {data?.streamer_ext?.name}
            </Text>
            <View style={tailwind("flex-row flex-wrap mt-1.5")}>
              <View
                style={tailwind(
                  "flex-row items-center py-0.5 px-2 mr-2 bg-[#FFFFFF1A] rounded-full"
                )}
              >
                <NativeImage
                  source={require("../../../assets/icon/12DP/ID.png")}
                />
                <Text style={tailwind("text-white text-xs font-medium ml-0.5")}>
                  {data?.streamer_ext?.user_id}
                </Text>
              </View>
              <View
                style={tailwind(
                  "flex-row items-center py-0.5 px-2 mr-2 bg-[#FFFFFF1A] rounded-full"
                )}
              >
                <Icon
                  type="ionicon"
                  name="calendar-outline"
                  size={12}
                  color="white"
                />
                <Text style={tailwind("text-white text-xs font-medium ml-0.5")}>
                  {formatDate(data?.ct)}
                </Text>
              </View>
            </View>
          </View>
          {data?.visitor_role === 3 && (
            <Icon name="chevron-forward-outline" type="ionicon" color="white" />
          )}
        </TouchableOpacity>
        <SettingItem title="分享空间" to="ShareSpace" />
        {data?.visitor_role === 3 && (
          <SettingItem title="空间付费设置" to="SpacePaymentSetting" />
        )}
        {data?.visitor_role === 3 && !isAgencyHided && (
          <SettingItem title="代运营设置" to="AgencySetting" />
        )}
        {(data?.visitor_role === 1 || data?.visitor_role === 2) && (
          <SettingItem title="合伙人设置" to="CollaboratorSetting" />
        )}
        {data?.visitor_role === 3 && (
          <SettingItem title="空间成员" to="SpaceMember" />
        )}
        {data?.refund_enable === 1 &&
          data?.admission_price > 0 &&
          data?.visitor_role === 0 && (
            <SettingItem title="申请退款" to="SpaceRefund" />
          )}
        {data?.visitor_role === 0 && (
          <>
            <TouchableOpacity
              onPress={() => setIsExitSpaceModalVisible(true)}
              style={tailwind("flex-row justify-between pt-4 pb-2")}
            >
              <Text style={tailwind("text-base text-white")}>退出空间</Text>
              <Icon
                name="chevron-forward-outline"
                type="ionicon"
                color="white"
              />
            </TouchableOpacity>
            <MyDivider />
          </>
        )}
      </ScrollView>
      <MyModal
        visible={isExitSpaceModalVisible}
        setVisible={setIsExitSpaceModalVisible}
        title="是否确认退出空间？"
        content="一旦退出，您的空间成员身份将会被取消，若当前空间为付费空间，下次加入时，需要再次付费。请确保知晓以上内容后谨慎选择退出。"
        highlightCancel
        cancel={() => {
          setIsExitSpaceModalVisible(false);
        }}
        confirm={() => {
          setIsExitSpaceModalVisible(false);
          handleExitSpace();
        }}
        confirmLeft
      />
    </View>
  );
}
