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

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

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

  const searchRef = useRef(null);

  const [search, setSearch] = useState("");
  const [result, setResult] = useState([]);
  const [isloading, setIsloading] = useState(false);
  const updateSearch = (search) => {
    setSearch(search);
    if (!search) return;
    setIsloading(true);
  };

  //进入页面默认focus
  useEffect(() => {
    searchRef.current.focus();
  }, []);

  //搜索框文本变化时进行搜索
  useEffect(() => {
    if (!search) {
      setResult([]);
      return;
    }
    const isNumeric = (str) => {
      return /^\d+$/.test(str);
    };
    const getResult = async () => {
      const apiUrl = process.env.EXPO_PUBLIC_API_URL;
      const isSearchInt = isNumeric(search);
      let api;
      let querryParams;
      if (isSearchInt) {
        api = "/api/streamer/list_ext_fuzzily_by_user_id";
        querryParams = { user_id: parseInt(search, 10) };
      } else {
        api = "/api/streamer/list_ext_fuzzily_by_name";
        querryParams = { name: search };
      }
      try {
        const base = await baseRequest();
        const signature = await generateSignature({
          ...base,
          ...querryParams,
          offset: 0,
          limit: 20,
        });
        const response = await fetch(`${apiUrl}${api}?signature=${signature}`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...base,
            ...querryParams,
            offset: 0,
            limit: 20,
          }),
        });
        const data = await response.json();
        if (data.ret === -1) {
          Toast.show({
            type: "error",
            text1: data.msg,
            topOffset: 60,
          });
          return;
        }
        if (!ignore) {
          setResult(data.data.list);
        }
        setIsloading(false);
      } catch (error) {
        console.error(error);
      }
    };
    let ignore = false;
    getResult();
    return () => {
      ignore = true;
    };
  }, [search]);

  //搜索项组件
  const renderItem = ({ item }) => {
    return (
      <ListItem
        onPress={() =>
          navigation.navigate("StreamerProfile", {
            mid: item.mid,
          })
        }
        bottomDivider
        containerStyle={tailwind("p-0 bg-[#07050A]")}
      >
        <View style={tailwind("flex-1")}>
          <View style={tailwind("flex-row py-3")}>
            <Image
              style={tailwind("w-12 h-12 rounded-full")}
              source={item?.avatar?.images[0]?.urls[0]}
              placeholder={blurhash}
              contentFit="cover"
              transition={1000}
              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?.name}
                </Text>
                <View
                  style={tailwind(
                    "flex-row items-center py-0.5 px-2 ml-1 bg-[#FFFFFF1A] rounded-full"
                  )}
                >
                  <NativeImage
                    source={require("../../assets/icon/12DP/ID.png")}
                  />
                  <Text
                    style={tailwind("text-white text-xs font-medium ml-0.5")}
                  >
                    {item?.user_id}
                  </Text>
                </View>
              </View>
              <Text
                style={tailwind("text-sm text-[#FFFFFF80]")}
                numberOfLines={1}
                ellipsizeMode="tail"
              >
                {item.bio}
              </Text>
            </View>
          </View>
        </View>
      </ListItem>
    );
  };

  return (
    <View
      style={{
        paddingTop: insets.top,
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
        ...tailwind("flex-1"),
      }}
    >
      <View style={tailwind("flex-row px-2 items-center")}>
        <Icon
          type="ionicon"
          name="chevron-back"
          size={32}
          color="white"
          onPress={() => navigation.goBack()}
        />
        <SearchBar
          ref={searchRef}
          containerStyle={tailwind("flex-1 bg-[#07050A]")}
          inputContainerStyle={tailwind("h-10 bg-[#FFFFFF1A]")}
          inputStyle={tailwind("text-white")}
          placeholder="搜索Ta的昵称或id"
          platform="ios"
          cancelButtonProps={tailwind("text-[#FF669E]")}
          cancelButtonTitle="清空"
          clearIcon={() => <></>}
          searchIcon={() => <></>}
          showLoading={isloading}
          onChangeText={updateSearch}
          value={search}
        />
      </View>
      <View style={tailwind("flex-1 px-4")}>
        <FlatList
          data={result}
          renderItem={renderItem}
          initialNumToRender={20}
          ListEmptyComponent={<Empty type={search ? "search" : "nodata"} />}
        />
      </View>
    </View>
  );
}
