import { View, 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 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 ? `genAvatarVideo${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);
    }
    if(data?.data.status === 'process_fail'){
      setShouldPoll(false);
    }
    return ()=> {
      
    }
  }, [data])


  const genVideo = () => {

  }

  const renderProgressStatus = () => {
    if(data?.data.status === 'process_fail'){
      return <View className="gradient-text">AI生成失败</View>
    }
    if(data?.data.status === 'success'){
      return <View className="gradient-text">AI生成成功</View>
    }
    return <View className="text-gray-500">AI生中</View>
  }


  

  return (
    <View>
      <View className={style.pickContainer}>
        <View className={`${style.pickAvatarCard} ${style.pickGenCard}`}>
          <View className="flex items-center gap-4">
            <IconStarColor></IconStarColor>{" "}
            {renderProgressStatus()}
          </View>
        </View>
      </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>
  );
});
