import { View,Text, Image } from "@tarojs/components";
import React, { useState, useCallback, useEffect } from "react";
import style from './index.module.less'
import IconChange from "@/components/icon/icon-change";
import IconStar from "@/components/icon/icon-star";
import WemetaTextarea from "@/components/wemeta-textarea/index";
import Taro, { useRouter } from "@tarojs/taro";
import { uploadAvatar } from '@/service/storage'
import { isSuccess } from "@/utils";
import { getNewAvatarPic } from "@/utils/avatar";
interface IProps {
  next: () =>void
  setTaskId: (value:any)=> void
}

export default React.memo(function StepStart({ next, setTaskId }: IProps) {

  const router = useRouter();
  const { avatarUrl } = router.params
  const uploadedAvatarUrl = decodeURIComponent(avatarUrl ?? '')
  const [currentAvatarUrl, setCurrentAvatarUrl] = useState(uploadedAvatarUrl)
  const [value, setValue] = useState('');
  const [loading, setLoading] = useState(false)
  const handleChange = () => {
    setLoading(true)
    getNewAvatarPic((picUrl)=> {
      picUrl && setCurrentAvatarUrl(picUrl)
      setLoading(false)
    })
  }

  const handleInput = (value: string) => {
    setValue(value);
  }

  const handleClick = async () => {
    if(loading){
      return;
    }
    if(!currentAvatarUrl.length){
      return
    }

    Taro.showLoading();
    console.log({
      aiGenerated: true,
      avatarUrl: currentAvatarUrl,
      description: value,
    })
    const response = await uploadAvatar({
      aiGenerated: true,
      avatarUrl: currentAvatarUrl,
      description: '',
    })
    Taro.hideLoading();
    if(isSuccess(response.status)){
      setTaskId(response.data.taskId)
      setTimeout(()=> next(), 200)
    }
  };

  return (
    <View>
      <View className={style.startContainer}>
        <View className={style.startCard}>
          <View className={style.startIconChange} onClick={handleChange}>
            <IconChange />
          </View>
          <Image className={style.startCardImage} src={currentAvatarUrl} mode="widthFix"></Image>
        </View>
        <View className="text-12 text-gray-4 mt-16 text-center">用于头像或聊天背景</View>
      </View>
      <View className="bottom-bar">
        <View className="px-20 py-12">
          <View className={`button-rounded-big gap-4 ${style.startGenButton}`} onClick={handleClick}>
            <IconStar />
            <View>生成AI形象</View>
          </View>
        </View>
      </View>
    </View>
  );
});
