import { View } from "@tarojs/components";
import IconStarColor from "@/components/icon/IconStarColor";
import { textPolishing } from '@/service/agent'
import { isSuccess } from "@/utils";
import { useState } from "react";
import Taro from '@tarojs/taro';
interface Props {
  text: string;
  type: "personality" | "greeting"
  onPolished: (text:string|null) => void
  onStateChange: (loading: boolean) => void
}
const Index = ({
  text,
  type,
  onPolished,
  onStateChange,
}: Props) => {
  const [isLoading, setIsLoading] = useState(false)
  const disabled =  text.length < 2
  const handleClick = async () => {
    // console.log('请求服务端润色')
    if(isLoading || disabled){
      return
    }
    setIsLoading(true)
    onStateChange(true)
    try{
      Taro.showLoading()
      const response = await textPolishing({
        content: text,
        type: type
      })
      Taro.hideLoading()
      setIsLoading(false)
      onStateChange(false)
      if(isSuccess(response.status)){
        onPolished(response.data?.content)
      }
    }catch(e){
      Taro.hideLoading()
      setIsLoading(false)
      onStateChange(false)
    }
  }

  return (
    <View className={`flex items-center gap-4 ${disabled ? 'opacity-20' : ''}`} onClick={handleClick}>
      {!isLoading ? <View className="text-primary flex flex-center"><IconStarColor color="blue"></IconStarColor><View>润色</View></View> : <View className="flex flex-center"><IconStarColor color="colorful"></IconStarColor><View className="gradient-text">润色中...</View></View>}
    </View>
  );
};
export default Index;
