import { View, Text } from "@tarojs/components";

import IconVoiceColor from "@/components/icon/icon-voice-color";
import CardList from "@/components/list/card-list";
import CardListItem from "@/components/list/card-list-item";

import IconIdeaColor from "@/components/icon/icon-idea-color";
import WemetaTextareaAI from '@/components/WemetaTextareaAI'

import IconArrow from "@/components/icon/icon-arrow";
import Taro from "@tarojs/taro";
import { useVoiceStore } from "@/store/voiceStore";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
import { forwardRef, useImperativeHandle, useRef } from "react";

export default forwardRef(function Index(props, ref) {

  const agentEdit = useAgentStore((state) => state.agentEdit)
  const { updateEditAgent } = useAgentStoreActions()

  // Create refs for the TextPolish components
  const personalityPolishRef = useRef<{ handleClick: () => void }>(null);
  const greetingPolishRef = useRef<{ handleClick: () => void }>(null);

  // Expose methods to parent components
  useImperativeHandle(ref, () => ({
    polishAllTexts: async () => {
      // Call both polish functions if they exist
      if (personalityPolishRef.current) {
        if(!agentEdit?.personality){
          await personalityPolishRef.current.handleClick();
        }

      }
      if (greetingPolishRef.current) {
        if(!agentEdit?.greeting){
          await greetingPolishRef.current.handleClick();
        }
      }
    }
  }));

  // 根据模式获取显示值
  const getDisplayValue = (field: string) => {
    return agentEdit?.[field] ?? ''
  }

  const { setEntId } = useVoiceStore()
  const handleEditVoice = () => {
    // 提前设置当前智能体 entId
    setEntId(agentEdit?.entId ?? 0);
    Taro.navigateTo({ url: '/pages/voice/index' })
  }

  // 处理表单字段更新
  const handleFieldChange = (field: string, value: string) => {
    console.log(field, value)
    updateEditAgent({ [field]: value });
  };

  const IconArrowRight = () => {
    return (
      <View className="flex items-center">
        <IconArrow />
      </View>
    );
  };

  // 如果有智能体名字，且名字字符串大于 2
  const hasName = (agentEdit?.name && agentEdit.name.length >= 2)
  const defalutPolishPersonality = hasName ? `你是 ${agentEdit?.entName} 的 ${agentEdit?.position} ${agentEdit?.name}`: ''
  const defalutPolishGreeting = hasName ? `我是 ${agentEdit?.name}，很高兴认识你！有什么想聊的或者想解决的问题吗`: ''

  const questionGuides = agentEdit?.questionGuides ?? [];
  const voiceName = agentEdit?.voiceName ?? '';

  return (
    <View className="flex flex-col gap-12">
      <WemetaTextareaAI
        aiType="personality"
        defaultAiTips={defalutPolishPersonality}
        prefix={() => <View>人设</View>}
        placeholder="示例：你是一名汽车销售人员，拥有专业的汽车相关知识，善于耐心的解答客户提出的每一个问题，并会主动邀请客户上门试驾。"
        value={getDisplayValue('personality')}
        cursorSpacing={20}
        autoHeight
        ref={personalityPolishRef}
        onInput={(value) => {
          handleFieldChange('personality', value)
        }}
      />

      <WemetaTextareaAI
        aiType="greeting"
        defaultAiTips={defalutPolishGreeting}
        cursorSpacing={20}
        prefix={() => <View>开场白</View>}
        placeholder="开场白是你的智能体和用户说的第一句话，简单做个自我介绍吧"
        value={getDisplayValue('greeting')}
        autoHeight
        ref={greetingPolishRef}
        onInput={(value) => {
          handleFieldChange('greeting', value)
        }}
      />
      <CardList>
        <CardListItem
          className="pl-16 pr-8"
          rightRenderer={IconArrowRight}
          leftRenderer={IconIdeaColor}
          onClick={() => {
            Taro.navigateTo({ url: '/pages/editor-pages/editor-greeting-questions/index' })
          }}
        >
          <View className="text-14 py-18 font-medium leading-22 flex items-center">
            <View className="flex-1">开场提问引导</View>
            <View className="text-gray-4">
              { questionGuides.length === 0 ? '去编辑' : `${questionGuides.length} / 3 ` }
            </View>
          </View>
        </CardListItem>
      </CardList>
      <CardList>
        <CardListItem
          className="pl-16 pr-8"
          underline
          rightRenderer={IconArrowRight}
          leftRenderer={IconVoiceColor}
          onClick={handleEditVoice}
        >
          <View className="text-14 py-18 font-medium leading-22 flex items-center">
            <View className="flex-1">声音</View>
            <View className="text-gray-4">
              {voiceName ? `${voiceName}` : "设置专属声音"}
            </View>
          </View>
        </CardListItem>
      </CardList>
    </View>
  );
})
