import { IconButton } from "@/components/ui/button";
import VoiceToneSlider from "./VoiceToneSlider";
import { cn } from "@/lib/utils";
import { useCreateDict } from "@/hooks/create";
import { WaveAnimation } from "@/components/ui/wave-animation";
import { useVoiceTTS } from "@/hooks/useVoiceTTS";
import { useMemo, useEffect } from "react";

const VoiceSelector = ({
  value,
  onChange,
  error,
  onPlay,
  playing,
  onStop,
}: {
  value: {
    tone: number;
    speed: number;
    content?: string | undefined;
  };
  onChange: (value: {
    tone: number;
    speed: number;
    content?: string | undefined;
  }) => void;
  error?: boolean;
  onPlay?: (code: string, audioUrl?: string) => void;
  playing?: boolean;
  onStop?: () => void;
}) => {
  const { data: dict } = useCreateDict();
  const timbreDictList = dict?.timbreDictList || [];

  const timbreDict = timbreDictList.find(item => item.code === value.content);
  const { name, voiceType, voiceText } = timbreDict || {};

  // 语音合成配置
  const ttsConfig = useMemo(() => {
    if (!voiceType || !voiceText) return null;
    
    // 将UI参数映射到TTS接口参数
    // tone: [-50, 100] 映射音量 (loudnessRate)
    // speed: [-50, 100] 映射语速 (speechRate)
    const loudnessRate = value.tone;
    const speechRate = value.speed;
    
    return {
      text: voiceText,
      // text: "Close your eyes — imagine small cottage by the sea. Sunrises paint sky in colors we've only dreamed of now.",
      // text: "Hi there! I'm just your friendly next-door neighbor, popping by to say hello! Got a moment to chat? I’d love to hear about your day or maybe share a fun little story!",
      // text: "You hold my heart, every beat a promise of devotion.",
      // text: "Good evening, my love. I made your favorite tea and cookies. Let's sit by the fire and share our day, just you and me.",
      // text: "Hello, darling. I missed you today. Come here for a hug. Tell me all about your day, I'm listening.",
      voiceType: voiceType,
      speechRate: speechRate,
      pitchRate: loudnessRate
    };
  }, [voiceType, voiceText, value.tone, value.speed]);

  // 语音合成Hook
  const {
    isGenerating,
    generateAudioUrl,
    getCachedBlobUrl,
  } = useVoiceTTS({
    cacheEnabled: true,
  });

  // 检查是否正在播放TTS
  
  // 播放控制逻辑
  const handlePlayClick = async () => {
    if (isGenerating) return;
    if (ttsConfig) {
      // 优先使用TTS生成的语音
      try {
        onStop?.();
        const audioUrl = await generateAudioUrl(ttsConfig);
        const playCode = (value.content?.toString() || "") + "TTS";
        onPlay?.(playCode, audioUrl);
      } catch (error) {
        console.error('TTS生成失败', error);
      }
    } else {
      console.error('TTS配置错误');
    }
  };

  // 显示状态：TTS播放 > 原始播放 > 生成中 > 默认
  const showPlaying = playing;
  const showGenerating = isGenerating && !showPlaying;
  
  if (!value.content) {
    return (
      <div className={cn("bg-surface-nest-normal rounded-sm p-4", error && "border border-important-variant-normal")}>
        <div className="w-full h-30 flex flex-col gap-3 justify-center items-center text-txt-secondary-normal border border-dashed border-txt-tertiary-normal rounded-sm">
          <i className="iconfont icon-Voice !text-[32px]" />
          <div className="text-txt-secondary-normal txt-label-l">
            Select the character's voice
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="bg-surface-element-normal rounded-sm p-4 flex flex-col gap-4">
      <div className="flex justify-between items-center">
        <span className="text-txt-primary-normal txt-label-m">
          {name}
        </span>
        <IconButton variant="tertiary" size="xs" onClick={() => {
          onChange({ ...value, content: "" });
          onStop?.();
        }}>
          <i className="iconfont icon-close" />
        </IconButton>
      </div>

      {/* 音高滑块 */}
      <VoiceToneSlider
        label="Pitch"
        value={value.tone}
        onChange={v => {
          onStop?.();
          onChange({ ...value, tone: v })
        }}
        min={-12}
        max={12}
      />
      <div>
        pitch_rate: {value.tone}
      </div>
      {/* 语速滑块 */}
      <VoiceToneSlider label="Speed" value={value.speed} onChange={v => {
        onStop?.();
        onChange({ ...value, speed: v })
      }} min={-50} max={100} />
      <div>
        speech_rate: {value.speed}
      </div>

      {/* 播放按钮区域 */}
      <div className="flex items-center justify-center gap-2 cursor-pointer" onClick={handlePlayClick}>
        <IconButton 
          type="button" 
          variant="default" 
          size="small" 
          disabled={isGenerating}
          loading={showGenerating}
        >
          {
            showPlaying
            ? <WaveAnimation className="text-txt-primary-normal animate-pulse" />
            : <i className="iconfont icon-Play text-txt-primary-normal" />
          }
        </IconButton>
        <div className="flex flex-col items-center">
          <span className="text-primary-variant-normal txt-label-l">
            Play Sample
          </span>
        </div>
      </div>
    </div>
  );
}
 
  export default VoiceSelector;