import { useEffect, useRef, useState } from "react";
import { Image, View, ScrollView, Video } from "@tarojs/components";
import { formatSeconds } from "@/utils/index";
import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";

import { uploadAndNavToGenNewAvatar } from "@/utils/avatar";
import IconPlusBig from "@/components/icon/icon-plus-big";

import { editAgentAvatar } from "@/service/agent";
import { deleteAvatar, fetchMyAvatars } from "@/service/storage";

import style from "./index.module.less";
import { TAvatarItem } from "@/service/storage";
import { useAgentStore } from "@/store/agentStore";

import Taro, { useDidShow } from "@tarojs/taro";
import { isSuccess } from "@/utils";
import IconDeleteGray16 from "@/components/icon/IconDeleteGray16";
import { useModalStore } from "@/store/modalStore";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";

export default function Index() {
  const { agent, fetchAgent } = useAgentStore();
  const [scrollTop, setScrollTop] = useState(0);
  const scrollPositionRef = useRef(0);

  const { showModal } = useModalStore();

  const fetcher = async ([_url, { pageIndex, pageSize }]) => {
    const res = await fetchMyAvatars({ pageIndex: pageIndex, pageSize });
    return res.data;
  };

  const { list, loadMore, mutate } = useLoadMoreInfinite<TAvatarItem[]>(
    createKey("fetchMyAvatars"),
    fetcher
  );

  const [current, setCurrent] = useState<TAvatarItem | null>(null);

  const handleClick = async (item: TAvatarItem) => {
    console.log(item);
    if (!agent?.agentId) {
      return;
    }

    Taro.showLoading();
    const result = await editAgentAvatar(agent.agentId, item.avatarId, true);
    await fetchAgent(agent.agentId);
    Taro.hideLoading();
    setCurrent(item);
    if (isSuccess(result.status)) {
      Taro.navigateBack();
    }
  };
  const onScrollToLower = () => {
    loadMore();
    console.log("lower");
  };
  const handleCreate = () => {
    uploadAndNavToGenNewAvatar();
  };

  const handleDelete = async (e: any, avatar: TAvatarItem) => {
    e.stopPropagation();
    showModal({
      content: <>确认删除该形象？</>,
      async onConfirm() {
        const response = await deleteAvatar(avatar.avatarId);
        if (isSuccess(response.status)) {
          mutate();
        }
      },
    });
  };

  useDidShow(()=> {
    mutate()
  })

  const renderMedia = (avatar: TAvatarItem) => {
    if (avatar.isVideo) {
      return <>
        <View className={style.videoContainer}>
          <Video
            controls={false}
            showCenterPlayBtn={false}
            loop={true}
            muted={true}
            objectFit="cover"
            src={avatar.avatarUrl}
            className="w-full h-full"
          />
          <View className={style.durationStatus}>
            <View className={style.playBtn}></View>
            <View>{formatSeconds(Math.round(avatar.videoSeconds))}</View>
          </View>
        </View>
      </>
    }
    return <Image src={avatar.avatarUrl} mode="widthFix" className="w-full" />;
  };

  const renderList = () => {
    if (!list.length) {
      return (
        <>
          {/* <EmptyData type={"search"}></EmptyData> */}
        </>
      );
    }

    return list.map((avatar) => {
      const isCurrent = agent?.avatarUrl === avatar.avatarUrl;
      return (
        <View
          className={`${isCurrent ? style.gridItemActived : style.gridItem}`}
          onClick={() => handleClick(avatar)}
        >
          {avatar.canDel && (
            <View
              className={style.deleteButton}
              onClick={(e) => handleDelete(e, avatar)}
            >
              <IconDeleteGray16 />
            </View>
          )}

          {renderMedia(avatar)}
        </View>
      );
    });
  };

  return (
    <PageCustom>
      <NavBarNormal>历史形象</NavBarNormal>
      <View className={style.container}>
        <ScrollView
          scrollY
          onScrollToLower={onScrollToLower}
          scrollTop={scrollTop}
          onScroll={(e) => {
            scrollPositionRef.current = e.detail.scrollTop;
          }}
          style={{
            flex: 1,
            height: "100%", // 高度自适应
          }}
        >
          <View className="w-full p-16 pb-120">
            <View className={style.grid}>
              <View className={style.gridItem} onClick={handleCreate}>
                <View className={style.icon}>
                  <IconPlusBig></IconPlusBig>
                </View>
                <View className="pt-8 text-12 leading-20 text-gray-45">
                  创建新形象
                </View>
              </View>
              {renderList()}
            </View>
          </View>
        </ScrollView>
      </View>
    </PageCustom>
  );
}
