import { View, Swiper, SwiperItem, Image } from "@tarojs/components";
import React, { useEffect, useState } from "react";
import { AvatarMedia } from "@/components/AvatarMedia";
import style from "./index.module.less";
import IconStarColor from "@/components/icon/IconStarColor";
import { getUploadedAvatarStatus, genAvatarVideo, type TAvatarItem } from '@/service/storage'
import useSWR from 'swr';
import Taro from "@tarojs/taro";
import { isSuccess } from "@/utils";
import WemetaButton from '@/components/buttons/WemetaButton'
interface IProps {
  prev: () => void;
  next: () => void;
  setPickedAvatar: (pickedAvatar: TAvatarItem)=> void
  avatars: TAvatarItem[],
  videos: TAvatarItem[],
  setAvatars: (avatars: TAvatarItem[])=> void
  setVideos: (avatars: TAvatarItem[])=> void
  taskId: string|number
}
export default React.memo(function Index({ prev, next, taskId, avatars, videos, setVideos, setAvatars, setPickedAvatar }: IProps) {
  const [currentSwiperIndex, setCurrentSwiperIndex] = useState(0);
  const [shouldPoll, setShouldPoll] = useState(false);
  const [videoGenerating, setVideoGenerating] = useState(false);
  const [currentTaskId, setCurrentTaskId] = useState<string|number>(taskId);
  const [displayText, setDisplayText] = useState<'initial' | 'updated'>('initial');

  // Reset display text when videoGenerating changes
  useEffect(() => {
    setDisplayText('initial');
  }, [videoGenerating]);

  // Handle the display text timing
  useEffect(() => {
    let timer: NodeJS.Timeout;

    if (!videoGenerating) {
      // For non-video generation
      if (displayText === 'initial') {
        timer = setTimeout(() => {
          setDisplayText('updated');
        }, 10000); // 10 seconds
      }
    } else {
      // For video generation
      if (displayText === 'initial') {
        timer = setTimeout(() => {
          setDisplayText('updated');
        }, 20000); // 20 seconds
      }
    }

    return () => {
      if (timer) clearTimeout(timer);
    };
  }, [videoGenerating, displayText]);

  const avatarsList = (videoGenerating) ? videos : avatars

  const goNext = () => {
    const pickedAvatar = avatarsList[currentSwiperIndex]
    if(!pickedAvatar){
      Taro.showToast({
        title: '没有对应的形象'
      })
      return
    }
    setPickedAvatar(pickedAvatar)
    console.log(pickedAvatar)
    next()
  }

  const handlePrev = () => {
    // 如果是生成微视频后，点击的上一步，则退回到生成微视频前
    if(videoGenerating){
      setVideoGenerating(false)
      setVideos([])
    }else{
      setShouldPoll(false);
      // 否则退回到生成 ai 图片的第一步
      prev()
    }
  }

  Taro.hideLoading()

  // 隔 3 秒轮询生成微视频任务
  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'){
      const results = data.data?.data
      if(videoGenerating){
        setVideos(results)
      }else{
        setAvatars(results)
      }
      setShouldPoll(false);
    }
    if(data?.data.status === 'process_fail'){
      setShouldPoll(false);
    }
    return ()=> {

    }
  }, [data])

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

  const isTaskProcessing = data?.data.status !== 'process_fail' && data?.data.status !== 'process_success'

  const genVideo = async () => {
    const a  = avatars[currentSwiperIndex]
    if(!a.avatarUrl){
      return
    }
    const avatarUrl = a.avatarUrl
    setVideoGenerating(true)
    // 清空 useSWR 缓存
    mutate(undefined, false);
    // 清空上一次可能生成的 videos
    setVideos([])
    setCurrentSwiperIndex(0)
    const response = await genAvatarVideo({avatarUrl})
    if(isSuccess(response.status)){
      setCurrentTaskId(response.data.taskId)
      setShouldPoll(true)
    }
  }


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

  const renderSwipers = () => {
    const renderIndicator = (currentIndex: number) => {
      return (
        <>
          <View className={style.indicatorContainer}>
            {avatarsList.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)}
        >
          {avatarsList.map(avatar => {
            return <SwiperItem>
              <View className={style.swiperItem}>
                <AvatarMedia roundedFull={false} source={avatar.avatarUrl} className="w-full h-full" />
                {/* <Image
                  mode="widthFix"
                  src={avatar.avatarUrl}
                ></Image> */}
                {avatar.isOriginal && <View className={style.pickAvatarOriginal}>
                  <View>原图</View>
                </View> }
                {!avatar.isOriginal && <View className={style.aiTips}>图片由AI生成</View> }

              </View>
            </SwiperItem>
          })}
        </Swiper>
        {/* <!-- 自定义指示点容器 --> */}
        {renderIndicator(currentSwiperIndex)}
      </View>
    );
  };

  // 生成中提示文本
  const renderStatusText = () => {
    if (!videoGenerating) {
      // Non-video generation flow
      if (displayText === 'initial') {
        return <>预计等待时间：20秒</>;
      } else {
        return <>退出不影响生成</>;
      }
    } else {
      // Video generation flow
      if (displayText === 'initial') {
        return <>预计等待时间：1分钟</>;
      } else {
        return <>退出不影响生成速度</>;
      }
    }
  };



  const renderProcessingStatus = () => {
    const targetText = !videoGenerating ? '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 && !videoGenerating) || (videos.length)){

      return renderSwipers()
    }

    return <View className={`${style.pickAvatarCard} ${style.pickGenCard}`}>
      <View className="flex flex-col justify-center items-center gap-16">
        <View className="flex items-center gap-4">
          <IconStarColor></IconStarColor>{" "}
          {renderProcessingStatus()}
        </View>
        {isTaskProcessing && <View className="leading-18 text-12 text-primary">
          {renderStatusText()}
        </View>}
      </View>
    </View>
  }



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

      <View className="bottom-bar">
        <View className="flex items-center gap-8 px-20 py-12">
          <WemetaButton type="normal" disabled={videoGenerating && !videos.length}  className="w-[88px]" onClick={handlePrev}>重新上传</WemetaButton>
          {!videoGenerating &&  <WemetaButton className={`${style.pickBtnGenVideo}`} type="normal" onClick={genVideo} disabled={!avatars.length} >生成微视频</WemetaButton> }
          <WemetaButton className="flex-1" onClick={goNext} disabled={(!avatars.length && !videoGenerating) || (videoGenerating && !videos.length )} >使用这张</WemetaButton>
        </View>
      </View>
    </View>
  );
});
