import {
  View,
  Text,
  Image as NativeImage,
  TouchableOpacity,
  ScrollView,
} from "react-native";
import React, { useState, useCallback } from "react";
import { useTailwind } from "tailwind-rn";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Toast from "react-native-toast-message";
import { Image } from "expo-image";
import { useHeaderHeight } from "@react-navigation/elements";
import baseRequest from "../../utils/baseRequest";
import { generateSignature } from "../../utils/crypto";
import GetWechatModal from "../../components/GetWechatModal";
import SubmitWechatModal from "../../components/SubmitWechatModal";
import VideoModal from "../../components/VideoModal";
import SpaceIntroduceSkeleton from "./skeleton";
import { usePreventScreenCapture } from "expo-screen-capture";
import { useFocusEffect } from "@react-navigation/native";
import { useImageViewer } from "../../context/ImageViewProvider";

export default function SpaceIntroduce({ navigation, route }) {
  usePreventScreenCapture();
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();
  const headerHeight = useHeaderHeight();

  const { showImageViewer } = useImageViewer();

  const [data, setData] = useState({});
  const [isLoading, setIsloading] = useState(true);
  const getData = async () => {
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const signature = await generateSignature({
        mid: route.params.mid,
        ...base,
      });
      const _response = await fetch(
        `${apiUrl}/api/zone/list_by_mid?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            mid: route.params.mid,
            ...base,
          }),
        }
      );
      const _data = await _response.json();
      if (_data.ret === -1) {
        Toast.show({
          type: "error",
          text1: _data.msg,
          topOffset: 60,
        });
        return;
      }
      if (_data.data.list[0].visitor_role !== 4) {
        navigation.replace("StreamerSpace", { mid: route.params.mid });
        return;
      }
      setData({
        ..._data.data.list[0],
        refund_enable: _data.data.refund_enable,
        refund_status: _data.data.refund_status,
      });
      setIsloading(false);
    } catch (error) {
      console.error(error);
    }
  };
  useFocusEffect(
    useCallback(() => {
      getData();
    }, [])
  );

  const images = data?.streamer_ext?.album?.images?.map((image, index) => {
    if (index > 4) return;
    return image?.urls[0];
  });
  const imagesForImageViewer = images?.map((url) => ({ url }));

  //当空间价格为0时，直接加入空间
  const handleJoinFreeSpace = async () => {
    const apiUrl = process.env.EXPO_PUBLIC_API_URL;
    try {
      const base = await baseRequest();
      const body = {
        zid: data?.id,
        product_id: "h5_zone_admission",
        ...base,
      };
      const signature = await generateSignature(body);
      const _response = await fetch(
        `${apiUrl}/api/zone/free_join?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;
      }
      navigation.replace("StreamerSpace", { mid: route.params.mid });
    } catch (error) {
      console.error(error);
    }
  };

  //点击查看微信按钮
  const [isAddWechatModalVisible, setIsAddWechatModalVisible] = useState(false);

  //是否展示视频Modal
  const [showVideo, setShowVideo] = useState(false);

  //加载初始骨架屏
  if (isLoading) return <SpaceIntroduceSkeleton />;

  return (
    <View
      style={{
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <ScrollView>
        <View style={tailwind("absolute top-0 left-0")}>
          <Image
            source={data?.streamer_ext?.cover?.images[0]?.urls[0]}
            contentFit="cover"
            transition={500}
            cachePolicy="disk"
            style={{
              aspectRatio: "25/17",
              ...tailwind("w-full"),
            }}
          />
          <View
            style={{
              backgroundColor: "#000000B2",
              ...tailwind("absolute w-full h-full"),
            }}
          ></View>
        </View>
        <View
          style={{
            marginTop: headerHeight,
            ...tailwind("flex flex-row items-center px-4 h-24"),
          }}
        >
          <Image
            style={tailwind(
              "w-[4.6rem] h-[4.6rem] rounded-full border-2 border-white"
            )}
            source={data?.streamer_ext?.avatar?.images[0]?.urls[0]}
            contentFit="cover"
            transition={500}
            cachePolicy="disk"
          />
          <View style={tailwind("flex flex-col shrink 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"
                )}
              >
                <NativeImage
                  source={require("../../assets/icon/12DP/edit.png")}
                />
                <Text style={tailwind("text-white text-xs font-medium ml-0.5")}>
                  {data?.zone_moment_count}
                </Text>
              </View>
            </View>
          </View>
          <TouchableOpacity
            onPress={() => setIsAddWechatModalVisible(true)}
            style={tailwind("flex flex-col items-center ml-auto")}
          >
            <NativeImage
              source={require("../../assets/icon/others/wechat_bg.png")}
            />
            <Text style={tailwind("text-white text-xs font-medium mt-0.5")}>
              查看微信
            </Text>
          </TouchableOpacity>
        </View>
        <View
          style={tailwind(
            "flex flex-col w-full rounded-t-3xl bg-[#07050A] mt-4 p-4"
          )}
        >
          <View style={tailwind("flex flex-col items-start")}>
            <View>
              <Text style={tailwind("text-white text-lg font-medium")}>
                空间介绍
              </Text>
              <NativeImage
                style={{ right: -5, bottom: 1, ...tailwind("absolute") }}
                source={require("../../assets/icon/others/pinkline.png")}
              />
            </View>
          </View>
          <Text style={tailwind("text-white text-base mt-3")}>
            {data?.profile}
          </Text>
          <View style={tailwind("flex flex-row flex-wrap mt-2")}>
            <TouchableOpacity
              activeOpacity={1}
              onPress={() => {
                setShowVideo(true);
              }}
              style={tailwind("basis-1/3 p-0.5")}
            >
              <Image
                style={{
                  aspectRatio: "1/1",
                  ...tailwind("w-full rounded"),
                }}
                source={data?.streamer_ext?.shorts?.videos[0]?.cover_urls[0]}
                contentFit="cover"
                transition={500}
                cachePolicy="disk"
              />
              <View
                style={tailwind(
                  "flex absolute w-full h-full left-0 top-0 z-10 justify-center items-center"
                )}
              >
                <NativeImage
                  source={require("../../assets/icon/others/play.png")}
                />
              </View>
            </TouchableOpacity>
            {data?.streamer_ext?.album?.images?.map((item, index) => {
              if (index > 4) return;
              return (
                <TouchableOpacity
                  activeOpacity={1}
                  onPress={() => {
                    showImageViewer({
                      imageUrls: imagesForImageViewer,
                      index: index,
                    });
                  }}
                  key={index}
                  style={tailwind("basis-1/3 p-0.5")}
                >
                  <Image
                    style={{
                      aspectRatio: "1/1",
                      ...tailwind("w-full rounded"),
                    }}
                    source={item?.urls[0]}
                    contentFit="cover"
                    transition={500}
                    cachePolicy="disk"
                  />
                </TouchableOpacity>
              );
            })}
          </View>
          {data?.admission_price !== 0 && (
            <>
              <View style={tailwind("flex flex-col items-start mt-8")}>
                <View>
                  <Text style={tailwind("text-white text-lg font-medium")}>
                    付费须知
                  </Text>
                  <NativeImage
                    style={{ right: -5, bottom: 1, ...tailwind("absolute") }}
                    source={require("../../assets/icon/others/pinkline.png")}
                  />
                </View>
              </View>
              <Text style={tailwind("text-white text-base mt-3")}>
                1、加入后，您可以查看空间内相关内容；
              </Text>
              <Text style={tailwind("text-white text-base mt-1")}>
                2、本空间由空间主人自行创建，加入空间前请确认相关风险，本平台不提供相关保证，请避免上当受骗；
              </Text>
              <Text style={tailwind("text-white text-base mt-1")}>
                3、虚拟商品一经售出不予退款，请确认阅读上述条款并无异议后进行购买；
              </Text>
              <Text style={tailwind("text-white text-base mt-1")}>
                4、本平台不提供违法及色情内容，如您发现空间内存在以上内容，请联系人工客服举报处理。
              </Text>
            </>
          )}
        </View>
      </ScrollView>
      {data?.refund_status !== 1 && data?.refund_status !== 2 && (
        <View
          style={tailwind(
            "flex flex-row h-[4.5rem] py-2 px-6 items-center justify-center border-t border-[#FFFFFF26]"
          )}
        >
          <TouchableOpacity
            onPress={
              data?.admission_price === 0
                ? handleJoinFreeSpace
                : () =>
                    navigation.navigate("WebWithoutHeader", {
                      uri:
                        process.env.EXPO_PUBLIC_WEB_URL +
                        "/zone/pay/" +
                        data?.id +
                        "/h5_zone_admission/0",
                    })
            }
            style={tailwind(
              "flex flex-row items-center justify-center h-12 rounded-full px-10 bg-[#FF669E]"
            )}
          >
            {data?.admission_price !== 0 && (
              <NativeImage
                style={tailwind("ml-2")}
                source={require("../../assets/icon/others/money_pink.png")}
              />
            )}
            <Text style={tailwind("text-base text-white font-medium ml-2")}>
              {data?.admission_price === 0
                ? "免费加入"
                : `${data?.admission_price / 100}元立即加入`}
            </Text>
            <NativeImage source={require("../../assets/icon/32DP/link.png")} />
          </TouchableOpacity>
        </View>
      )}
      {/* 查看微信Modal */}
      {data?.streamer_ext?.wechat_lock_type === 0 ? (
        <GetWechatModal
          visible={isAddWechatModalVisible}
          setVisible={setIsAddWechatModalVisible}
          streamerMid={route.params.mid}
        />
      ) : (
        <SubmitWechatModal
          visible={isAddWechatModalVisible}
          setVisible={setIsAddWechatModalVisible}
          streamerMid={route.params.mid}
        />
      )}
      {/* 查看视频Modal */}
      <VideoModal
        visible={showVideo}
        setVisible={setShowVideo}
        url={data?.streamer_ext?.shorts?.videos[0]?.urls[0]}
      />
    </View>
  );
}
