import Taro, { useDidShow, useReachBottom } from "@tarojs/taro";
import { View, Text, ScrollView } from "@tarojs/components";
import EmptyData from "@/components/empty-data";
import NavBarNormal from "@/components/NavBarNormal/index";
import SearchBar from "@/components/search-bar/index";
import style from "./index.module.less";
import { useEffect, useState } from "react";
import ContactCard from "./components/contact-card/index";
import { getContactList, setContactToTop } from "@/service/contact";
import { useLoadMoreInfinite, type TResponseData } from "@/utils/loadMoreInfinite";
import PageCustom from "@/components/page-custom/index";
import { TContactItem } from "@/types/contact";
import { isSuccess } from "@/utils";
import { delContact } from "@/service/contact";
export default function Index() {
  const [searchValue, setSearchValue] = useState("");

  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 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 {list, setSize, mutate} = useLoadMoreInfinite<TContactItem[]>(getKey, fetcher)


  const resetFetchList = () => {
    setSize(1);
  };

  const handleSearchBarChanged = (v: string) => {
    setSearchValue(v);
  };

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

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


  const handleHello = async (e: any) => {
    const detail = e.detail as { type: string; id: string };
    console.log(detail);
    // 置顶与取消置顶
    if (detail.type === "pin" || detail.type === "unpin") {
      const reseponse = await setContactToTop({
        isTop: detail.type === "pin",
        contactId: detail.id,
      });
      if (isSuccess(reseponse.status)) {
        mutate()
        return;
      }
    }
    if(detail.type === 'delete'){
      handleDelete(detail.id)
    }
  };

  useDidShow(() => {
    mutate(undefined, {revalidate:true})
  })

  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 renderItem = (item)=> {
    // @ts-ignore
  return <slide-contact
    pid={item.contactId}
      pinned={item.isTop}
      onAction={handleHello}
    >
    <View className={`rounded-12 overflow-hidden ${item.isTop ? "bg-[#EDF1FF]" : "bg-white"}`}>
        <ContactCard
          refresh={mutate}
          deleteable={true}
          key={item.contactId}
          data={item}
          fromContact
        ></ContactCard>
      </View>
    </slide-contact>
  }

  const renderContent = () => {
    if (list?.length) {
      return list.map((item) => (
        <View className="rounded-24 bg-white">
          {renderItem(item)}
        </View>
      ));
    }
    return <EmptyData type={'search'} />;
  };

  return (
    <PageCustom fullPage>
      <NavBarNormal
        scrollFadeIn
        leftColumn={() => <Text className="text-16 font-medium">联系人</Text>}
      ></NavBarNormal>
      <View className="flex flex-col w-full">
        <View className="px-16 pb-14">
          <SearchBar
            value={searchValue}
            onChange={(e) => handleSearchBarChanged(e)}
            onClear={() => handleClear()}
          ></SearchBar>
        </View>
        <View className="rounded-container-header"></View>
        <View className="px-16 text-gray-45 text-12 leading-20 mb-20">
          共 4 个联系人
        </View>
        <ScrollView
          scrollY
          onScrollToUpper={onScrollToUpper}
          style={{
            flex: 1,
            height: "100%", // 高度自适应
          }}
        >
          <View className={style.contactContent}>{renderContent()}</View>  
        </ScrollView>
      </View>
    </PageCustom>
  );
}
