import { View, Swiper, SwiperItem, Image } from "@tarojs/components";
import React, { useEffect, useState } from "react";
import style from "./index.module.less";
import IconStarColor from "@/components/icon/icon-star-color";
import { getUploadedAvatarStatus, TAvatarItem } from '@/service/storage'
import useSWR from 'swr';
import Taro from "@tarojs/taro";
interface IProps {
  prev: () => void;
  next: () => void;
  setPickedAvatar: (pickedAvatar: TAvatarItem)=> void
  taskId: string|number
}
export default React.memo(function Index({ prev, next, taskId, setPickedAvatar }: IProps) {
  const [currentSwiperIndex, setCurrentSwiperIndex] = useState(0);
  const [avatars, setAvatars] = useState<TAvatarItem[]>([]);
  const [shouldPoll, setShouldPoll] = useState(false);
  
  
  const goNext = () => {
    const pickedAvatar = avatars[currentSwiperIndex]
    setPickedAvatar(pickedAvatar)
    console.log(pickedAvatar)
    next()
  }
  
  Taro.hideLoading()

  const { data } = useSWR(
    shouldPoll ? `getUploadedAvatarStatus${taskId}` : null,
    ()=> getUploadedAvatarStatus(taskId),
    {
      revalidateOnFocus: false,
      refreshInterval: shouldPoll ? 3000 : 0,
      refreshWhenHidden: false,
      refreshWhenOffline: false,
      revalidateOnMount: false
    }
  );

  useEffect(() => {
    setShouldPoll(true);
    return () => {
      setShouldPoll(false);
    };
  }, []);

  useEffect(()=> {
    if(data?.data.status === 'success'){
      setAvatars(data.data?.data.reverse())
      setShouldPoll(false);
    }
    return ()=> {
      
    }
  }, [data])
  

  const onSwiperChange = (e: any) => {
    const i = e.detail.current;
    setCurrentSwiperIndex(i);
  };



  

  const renderSwipers = () => {
    const renderIndicator = (currentIndex: number) => {
      return (
        <>
          <View className={style.indicatorContainer}>
            {avatars.map((_item, index) => {
              return (
                <View
                  key={index}
                  className={
                    index === currentIndex
                      ? `${style.indicator} ${style.indicatorActive}`
                      : style.indicator
                  }
                ></View>
              );
            })}
          </View>
        </>
      );
    };

    return (
      <View className={`${style.pickAvatarCard}`}>
        <Swiper
          className={style.mySwiper}
          indicatorColor="#999"
          indicatorActiveColor="#333"
          indicatorDots={false}
          duration={200}
          next-margin="-120rpx"
          current={currentSwiperIndex}
          onChange={(e) => onSwiperChange(e)}
        >
          {avatars.map(avatar => {
            return <SwiperItem>
              <View className={style.swiperItem}>
                <Image
                  mode="widthFix"
                  src={avatar.avatarUrl}
                ></Image>
                {avatar.isOriginal && <View className={style.pickAvatarOriginal}>
                  <View>原图</View>
                </View> }
              </View>
            </SwiperItem>
          })}
        </Swiper>
        {/* <!-- 自定义指示点容器 --> */}
        {renderIndicator(currentSwiperIndex)}
      </View>
    );
  };

  const renderContent = ()=> {
    if(avatars.length){
      return renderSwipers()
    }

    return <View className={`${style.pickAvatarCard} ${style.pickGenCard}`}>
      <View className="flex items-center gap-4">
        <IconStarColor></IconStarColor>{" "}
        <View className="gradient-text">AI生成中</View>
      </View>
    </View>
  }

  

  return (
    <View>
      <View className={style.pickContainer}>
        {renderContent()}
      </View>

      <View className="bottom-bar">
        <View className="grid grid-cols-2 gap-8 px-20 py-12">
          <View className={`button-rounded`} onClick={prev}>
            上一步
          </View>
          <View className={`button-rounded primary ${avatars.length ? '' : 'opacity-20'}`} onClick={()=> goNext()}>
            使用这张
          </View>
        </View>
      </View>
    </View>
  );
});
