import {
  Text,
  View,
  TouchableOpacity,
  Image as NativeImage,
  Alert,
} from "react-native";
import React, { useEffect, useState } from "react";
import { Image } from "expo-image";
import { useTailwind } from "tailwind-rn";
import { ListItem, Icon } from "@rneui/themed";
import { get } from "../../../utils/storeInfo";
import baseRequest from "../../../utils/baseRequest";
import { generateSignature } from "../../../utils/crypto";
import { useNavigation } from "@react-navigation/native";
import Banner from "../../../components/Banner";
import requireAPI from "../../../utils/requireAPI";
import * as Linking from "expo-linking";
import { goToPage } from "../../../utils/tools";
import { Platform } from "react-native";
export default function HostList() {
  const navigation = useNavigation();
  const tailwind = useTailwind();
  const [hostList, setHostList] = useState([]);
  const [bannerList, setBannerList] = useState([]);
  useEffect(() => {
    const getHostList = async () => {
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      let api;
      api = "/api/activity_hot/list";
      const account = await get("account");
      try {
        const base = await baseRequest();
        const signature = await generateSignature({
          ...base,
        });
        const response = await fetch(`${apiUrl}${api}?signature=${signature}`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
            mid: account.mid,
          }),
        });
        const data = await response.json();
        setHostList(data.data.list);
      } catch (error) {
        console.error(error);
      }
    };
    const getBannerList = async () => {
      try {
        const _data = await requireAPI(
          "POST",
          "/api/activity_banner/list",
          { body: { device_type: Platform.OS === "android" ? 0 : 1 } },
          true
        );
        if (_data.ret === -1) {
          Toast.show({
            icon: "fail",
            content: _data.msg,
            position: "top",
          });
          return;
        }
        const bannerList = _data.data.list.map((item) => {
          const links = item?.hyperlinks;
          let link = null;
          if (links.length > 1) {
            link = links.filter((it) => it.inward_action_type === "app")[0]
              ?.url;
          } else {
            link = links[0]?.url;
          }
          return {
            link: {
              url: link,
              action: links[0]?.action,
            },
            url: item?.image.images[0]?.urls[0],
            id: item?.id,
          };
        });
        setBannerList(bannerList);
      } catch (error) {
        console.error(error);
      }
    };
    getHostList();
    getBannerList();
  }, []);
  return (
    <View style={{ ...tailwind("flex-1"), paddingHorizontal: 16 }}>
      <View style={tailwind("flex flex-row justify-between items-center")}>
        <Text style={tailwind("text-white text-xl font-medium")}>猜你想看</Text>
        <TouchableOpacity
          onPress={() => navigation.navigate("Stream")}
          style={tailwind("flex flex-row justify-between items-center")}
        >
          <Text style={tailwind("text-[#FFFFFF80] text-sm font-medium")}>
            查看更多
          </Text>
          <Icon
            type="ionicon"
            name="chevron-forward"
            size={14}
            color="#FFFFFF80"
            onPress={() => navigation.goBack()}
          />
        </TouchableOpacity>
      </View>
      <View>
        {hostList.length > 0 &&
          hostList.map((item, index) => (
            <ListItem key={index} containerStyle={tailwind("p-0 bg-[#07050A]")}>
              <TouchableOpacity
                onPress={() => {
                  const links = item?.hyperlinks;
                  let link = null;
                  if (links.length > 1) {
                    link = links.filter((it) => it.action === "inward")[0]?.url;
                  } else {
                    link = links[0]?.url;
                  }
                  const linkAndParams = goToPage({
                    action: links[0]?.action,
                    url: link,
                  });
                  if (typeof linkAndParams === "string") {
                    if (
                      links[0]?.action === "webViewHeaderInward" ||
                      links[0]?.action === "webViewHeaderOutward"
                    ) {
                      navigation.navigate("WebWithHeader", {
                        title: "",
                        uri: linkAndParams,
                      });
                      return;
                    } else if (
                      links[0]?.action === "webViewWithOutHeaderInward" ||
                      links[0]?.action === "webViewWithOutHeaderOutward"
                    ) {
                      navigation.navigate("WebWithoutHeader", {
                        title: "",
                        uri: linkAndParams,
                      });
                      return;
                    }
                    try {
                      // 尝试启动微信客户端
                      Linking.openURL(linkAndParams).catch(() => {
                        // 启动微信客户端失败，弹出提示安装对话框
                        Alert.alert(
                          "错误提醒",
                          "打开链接失败，请返回重试或者联系在线客服",
                          [{ text: "确认", style: "cancel" }],
                          { cancelable: false }
                        );
                      });
                    } catch (error) {
                      // 启动微信客户端失败，继续加载URL
                      console.error(error);
                    }
                  } else {
                    navigation.navigate(...linkAndParams);
                  }
                }}
                style={tailwind("flex-row py-3")}
              >
                <Image
                  style={tailwind("w-12 h-12 rounded-full")}
                  source={item.image.images[0].urls[0]}
                  contentFit="cover"
                  cachePolicy="disk"
                />
                <View style={tailwind("ml-2 justify-around flex-1")}>
                  <View style={tailwind("flex flex-row items-center")}>
                    <Text
                      style={tailwind("text-base text-white font-medium")}
                      numberOfLines={1}
                      ellipsizeMode="tail"
                    >
                      {item.title}
                    </Text>
                    {index < 3 && (
                      <NativeImage
                        style={tailwind("ml-1")}
                        source={require("../../../assets/images/hot.png")}
                      />
                    )}

                    {!!item.age && (
                      <>
                        <View
                          style={tailwind(
                            "flex-row items-center py-0.5 px-2 ml-1 bg-[#FFFFFF1A] rounded-full"
                          )}
                        >
                          <NativeImage
                            source={
                              item.gender
                                ? require("../../../assets/icon/12DP/female.png")
                                : require("../../../assets/icon/12DP/male.png")
                            }
                          />
                          <Text
                            style={tailwind(
                              "text-white text-xs font-medium ml-0.5"
                            )}
                          >
                            {item.age}
                          </Text>
                        </View>
                        <View
                          style={tailwind(
                            "flex-row items-center py-0.5 px-2 ml-1 bg-[#FFFFFF1A] rounded-full"
                          )}
                        >
                          <NativeImage
                            source={require("../../../assets/icon/12DP/location.png")}
                          />
                          <Text
                            style={tailwind(
                              "text-white text-xs font-medium ml-0.5"
                            )}
                          >
                            {item.city}
                          </Text>
                        </View>
                      </>
                    )}
                  </View>
                  <Text
                    style={tailwind("text-sm text-[#FFFFFF80]")}
                    numberOfLines={1}
                    ellipsizeMode="tail"
                  >
                    {item.text}
                  </Text>
                </View>
              </TouchableOpacity>
            </ListItem>
          ))}
      </View>
      {/* Banner预留位置 */}
      <View style={tailwind("mt-4 mb-10")}>
        <Banner banners={bannerList} navigation={navigation} />
      </View>
    </View>
  );
}
