import Taro, { useDidShow, useReachBottom } from "@tarojs/taro";
import { View, Text, ScrollView } from "@tarojs/components";
import EmptyData from "@/components/EmptyData";
import NavBarNormal from "@/components/NavBarNormal/index";
import SearchBar from "@/components/search-bar/index";
import { useEffect, useState } from "react";
import ContactCard from "./components/contact-card/index";
import { getContactList, setContactToTop } from "@/service/contact";
import { useLoadMoreInfinite } from "@/utils/loadMoreInfinite";
import PageCustom from "@/components/page-custom/index";
import { TContactItem } from "@/types/contact";
import { isSuccess } from "@/utils";
import { delContact } from "@/service/contact";
import CheckLoginPopup from "@/components/CheckLoginPopup";
import BlurContainer from "@/components/BlurContainer";
import SliderAction from "@/components/SliderAction";
import PageTitle from '@/components/PageTitle'
export default function Index() {
  const [searchValue, setSearchValue] = useState("");
  // const [scrollIng, setScrolling] = useState(false);

  const fetcher = async ([_url, params, keyword]) => {
    params = params || {};
    console.log("fetcher", _url, params);
    const res = await getContactList({
      startId: params.nextId,
      pageSize: params.pageSize,
      keyword: keyword,
    });
    return res.data;
  };
  const [isInputting, setIsInputting] = useState(false);
  const [totalCount, setTotalCount] = useState<number>(0);
  const getKey = (pageIndex: number, previousPageData) => {
    if (pageIndex === 0)
      return ["/my/contacts", { nextId: undefined, pageSize: 10 }, searchValue];
    if (previousPageData && previousPageData.nextId) {
      return [
        "/my/contacts",
        { pageSize: 10, nextId: previousPageData.nextId },
        searchValue,
      ];
    }
    return null;
  };
  const { data, list, setSize, mutate, pageIndex } = useLoadMoreInfinite<
    TContactItem[]
  >(getKey, fetcher, {
    revalidateOnMount: false
  });

  // 修改搜索框的 onChange 和 onFocus/onBlur
  const handleSearchBarChanged = (v: string) => {
    setSearchValue(v);
  };

  const handleFocus = () => {
    setIsInputting(true);
  };

  const handleBlur = () => {
    // 延迟一点时间，避免 blur 后立即隐藏，影响输入法
    setTimeout(() => {
      setIsInputting(false);
    }, 100);
  };

  const handleClear = () => {
    setSearchValue("");
  };

  // 有联系人列表，或者搜索栏有值，说明是搜索结果，搜索结果有可能是 0 条记录
  const showSearchBar = totalCount > 0 || !!searchValue.length || isInputting;


  const onScrollToUpper = () => {
    // 加载更多数据
    // 如果搜索框中有数据由不加载更多数据
    if (searchValue.length) {
      return;
    }
    setSize((prevSize) => prevSize + 1);
  };

  const handleDelete = (contactId: string | number) => {
    Taro.showModal({
      content: "😭 确认删除该联系人吗？",
      async success(result) {
        if (result.confirm) {
          const response = await delContact(contactId);
          if (isSuccess(response.status)) {
            Taro.showToast({
              title: "删除成功",
              icon: "none",
            });
            mutate();
          }
        }
      },
    });
  };

  const handlePin = async (isTop: boolean, contactId: string | number) => {
    const reseponse = await setContactToTop({
      isTop: !isTop,
      contactId: contactId,
    });
    if (isSuccess(reseponse.status)) {
      mutate();
    }
  };

  useDidShow(() => {
    mutate();
  });
  const onLoginEnd = () => {
    mutate();
  };

  useEffect(() => {
    if (data && pageIndex === 1) {
      setTotalCount(data?.[0].totalCount || 0);
    }
  }, [data, pageIndex]);

  const createSliderButtons = (item: TContactItem) => {
    const onTopText = item.isTop ? (
      <View>
        <View>取消</View>
        <View>置顶</View>
      </View>
    ) : (
      "置顶"
    );
    return [
      {
        text: "删除",
        color: "#FF8200",
        onClick: () => {
          handleDelete(item.contactId);
        },
      },
      {
        text: onTopText,
        color: `${item.isTop ? "#FF4747" : "#327BF9"}`,
        onClick: () => {
          handlePin(item.isTop, item.contactId);
        },
      },
    ];
  };



  const renderContent = () => {
    if (list?.length) {
      return list.map((item) => (
        <View className={`rounded-12 overflow-hidden truncate`}>
          <SliderAction actions={createSliderButtons(item)} key={item.contactId}>
            <ContactCard
              refresh={mutate}
              deleteable={true}
              key={item.contactId}
              data={item}
              fromContact
              className={`${item.isTop ? "bg-[#EDF1FF]" : "bg-white"}`}
            ></ContactCard>
          </SliderAction>
        </View>
      ));
    }
    return <EmptyData text="暂无联系人" type={"search"} />;
  };

  const handleScrollEnd = ()=> {
    'worklet'
    console.log('scrollend')
  }

  return (
    <PageCustom fullPage isTabPage isflex>
      <NavBarNormal
        scrollFadeIn
        leftColumn={() => <PageTitle>联系人</PageTitle>}
      ></NavBarNormal>
      <View className="w-full h-full flex flex-col overflow-hidden">
        <View className="px-16 pb-14">
          {showSearchBar && (
            <SearchBar
              value={searchValue}
              onChange={handleSearchBarChanged}
              onFocus={handleFocus}
              onBlur={handleBlur}
              onClear={handleClear}
            ></SearchBar>
          )}
        </View>
        <BlurContainer className="flex flex-col overflow-hidden">
          <View className="px-16 text-gray-4 text-12 leading-20 mb-20 pt-16">
            共 {totalCount} 个联系人
          </View>
          <View className="flex-1 h-full overflow-hidden">
          <ScrollView
            scrollY
            onScrollToUpper={onScrollToUpper}
            style={{
              flex: 1,
              height: "100%", // 高度自适应
            }}
          >
            <View className="flex flex-col px-16 gap-8 pb-16">{renderContent()}</View>
          </ScrollView>
          </View>

        </BlurContainer>
      </View>
      <CheckLoginPopup onEnd={onLoginEnd}></CheckLoginPopup>
    </PageCustom>
  );
}
