import { View, Image, Text, ScrollView } from "@tarojs/components";
import { Input } from "@nutui/nutui-react-taro";
import { useEffect, useMemo, useRef } from "react";
import { useListState } from "@/store/listStore";
import { useGlobalState } from "@/store/global";
import { withAuth, GeneralNavbar } from "@/components";
import img from "@/config/images";
import "./index.scss";
import Taro from "@tarojs/taro";

const ListSearch = () => {
  const {
    searchValue,
    updateState,
    updateSearchPageState,
    getSearchHistory,
    clearHistory,
    searchSuggestion,
  } = useListState() || {};

  const {
    searchHistory = [],
    suggestionList,
    isShowSuggestion,
  } = useListState()?.searchPageState || {};
  const ref = useRef<any>(null);
  
  // 获取导航栏高度信息
  const { statusNavbarHeightInfo } = useGlobalState();
  const { totalHeight = 0 } = statusNavbarHeightInfo || {};

  useEffect(() => {
    getSearchHistory();
    return () => {
      handleClear();
    };
  }, []);

  useEffect(() => {
    if (ref?.current) {
      ref.current.focus();
    }
  }, [ref.current]);

  const regex = useMemo(() => {
    return new RegExp(searchValue, "gi");
  }, [searchValue]);

  // 是否显示清空图标
  const isShowClearIcon = searchValue && searchValue?.length > 0;

  // 是否显示搜索历史
  const isShowHistory = searchHistory && searchHistory?.length > 0;

  /**
   * @description 输入
   * @param value
   */
  const handleChange = (value: string) => {
    updateState({ searchValue: value });
    if (value) {
      searchSuggestion(value);
    } else {
      updateSearchPageState({
        isShowSuggestion: false,
      });
    }
  };

  /**
   * @description 点击清空输入内容
   */
  const handleClear = () => {
    updateState({ searchValue: "" });
    updateSearchPageState({
      isShowSuggestion: false 
    });
  };

  /**
   * @description 点击历史搜索
   * @param value
   */
  const handleHistoryClick = (item: { id: number; title: string }) => {
    updateState({ searchValue: item?.title });
    handleSearch(item?.title);
  };

  /**
   * @description 清空历史搜索
   */
  const handleClearHistory = () => {
    clearHistory();
  };

  /**
   * @description 点击联想词
   */
  const handleSuggestionSearch = (val: string) => {
    updateState({ searchValue: val });
    updateSearchPageState({
      isShowSuggestion: false,
    });
    handleSearch(val);
  };

  /**
   * @description 点击搜索
   */
  const handleSearch = (val?: string) => {
    if (!val) {
      return;
    }
    Taro.navigateTo({
      url: `/game_pages/searchResult/index`,
    });
  };

  return (
    <>
      <GeneralNavbar 
        title=""
        showBack={true}
      
      />
      <View 
        className="listSearchContainer"
        style={{ paddingTop: `${totalHeight}px` }}
      >
        {/* 搜索框 - 固定在顶部 */}
        <View className="topSearch">
          <Image className="searchIcon" src={img.ICON_LIST_SEARCH_SEARCH} />
          <Input
            placeholder="搜索球局和场地"
            value={searchValue}
            defaultValue={searchValue}
            onChange={handleChange}
            onClear={handleClear}
            autoFocus
            clearable={false}
            ref={ref}
          />
          <View className="searchRight">
            {isShowClearIcon && (
              <Image
                className="clearIcon icon16"
                src={img.ICON_LIST_SEARCH_CLEAR}
                onClick={handleClear}
              />
            )}
            <View className="searchLine" />
            <Text className="searchText" onClick={() => handleSearch(searchValue)}>
              搜索
            </Text>
          </View>
        </View>
        
        {/* 中间内容区域 - 可滚动 */}
        <ScrollView
          scrollY
          className="searchContentScroll"
          enhanced
          showScrollbar={false}
        >
          {/* 联想词 */}
          {isShowSuggestion && (
            <View className="searchSuggestion">
              {(suggestionList || [])?.map((item) => {
                // 替换匹配文本为高亮版本
                const highlightedText = item.replace(regex, (match) => {
                  // 如果匹配不到，则返回原文本
                  if (!match) return match;
                  return `<Text class="highlight">${match}</Text>`;
                });
                return (
                  <View
                    className="searchSuggestionItem"
                    onClick={() => handleSuggestionSearch(item)}
                  >
                    <View className="searchSuggestionItemLeft">
                      <Image
                        className="icon16"
                        src={img.ICON_LIST_SEARCH_SEARCH}
                      />
                      <Text
                        dangerouslySetInnerHTML={{ __html: highlightedText }}
                      ></Text>
                    </View>
                    <Image
                      className="icon16"
                      src={img.ICON_LIST_SEARCH_SUGGESTION}
                    />
                  </View>
                );
              })}
            </View>
          )}
          {/* 历史搜索 */}
          {!isShowClearIcon && (
            <View className="historySearch">
              <View className="historySearchTitleWrapper">
                <View className="historySearchTitle">历史搜索</View>
                <View className="historySearchClear" onClick={handleClearHistory}>
                  <Text>清空</Text>
                  <Image
                    className="clearIcon icon16"
                    src={img.ICON_LIST_SEARCH_CLEAR_HISTORY}
                  />
                </View>
              </View>

              {isShowHistory && (
                <View className="historySearchList">
                  {(searchHistory || [])?.map((item) => {
                    if (!item?.title) {
                      return null;
                    }
                    return (
                      <Text
                        className="historySearchItem"
                        onClick={() => handleHistoryClick(item)}
                      >
                        {item?.title}
                      </Text>
                    );
                  })}
                </View>
              )}
            </View>
          )}
        </ScrollView>
      </View>
    </>
  );
};
export default withAuth(ListSearch);
