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, genAvatarVideo, type TAvatarItem } from '@/service/storage'
import useSWR from 'swr';
import Taro from "@tarojs/taro";
import { isSuccess } from "@/utils";
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 [videoGen, setVideoGen] = useState(false);
  const [currentTaskId, setCurrentTaskId] = useState<string|number>(taskId);
  
  const goNext = () => {
    const pickedAvatar = avatars[currentSwiperIndex]
    setPickedAvatar(pickedAvatar)
    console.log(pickedAvatar)
    next()
  }
  
  Taro.hideLoading()

  const { data, mutate } = useSWR(
    shouldPoll ? `getUploadedAvatarStatus${currentTaskId}` : null,
    ()=> getUploadedAvatarStatus(currentTaskId),
    {
      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);
    }
    if(data?.data.status === 'process_fail'){
      setShouldPoll(false);
    }
    return ()=> {
      
    }
  }, [data])


  const genVideo = async () => {
    const a  = avatars[currentSwiperIndex]
    if(!a.avatarUrl){
      return 
    }
    const avatarUrl = a.avatarUrl
    setVideoGen(true)
    // 清空 useSWR 缓存
    mutate(undefined, false); 
    setAvatars([]);
    const response = await genAvatarVideo({avatarUrl})
    if(isSuccess(response.status)){
      setCurrentTaskId(response.data.taskId)
      setShouldPoll(true)
    }
  }
  

  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 renderProcessingStatus = () => {
    const targetText = !videoGen ? 'AI' : '视频'
      
    if(data?.data.status === 'process_fail'){
      return <View className="gradient-text">{`${targetText}生成失败`}</View>
    }
    if(data?.data.status === 'success'){
      return <View className="gradient-text">{`${targetText}生成成功`}</View>
    }
    return <View className="gradient-text">{`${targetText}生成中`}</View>
  }

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

    return <View className={`${style.pickAvatarCard} ${style.pickGenCard}`}>
      <View className="flex items-center gap-4">
        <IconStarColor></IconStarColor>{" "}
        {renderProcessingStatus()}
      </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`} onClick={genVideo}>
            生成微视频
          </View>
          <View className={`button-rounded primary ${avatars.length ? '' : 'opacity-20'}`} onClick={()=> goNext()}>
            使用这张
          </View>
        </View>
      </View>
    </View>
  );
});
