import { View } from "@tarojs/components";
import React, { useEffect, useState, forwardRef, useImperativeHandle, useRef } from "react";
import AgentSettingList from './components/AgentSettingList'
import AgentKnowledgeLib from './components/AgentKnowledgeLib'
import AgentCard from './components/AgentCard'
import AgentContactCard from './components/AgentContactCard'
import BottomBar from "@/components/BottomBar";
import WemetaButton from "@/components/buttons/WemetaButton";



import { useAgentStore } from "@/store/agentStore";


export default forwardRef(function Index({save}: {save: ()=> void}, ref) {
  console.log('agent setting')
  const agentEdit = useAgentStore((state) => state.agentEdit)
  const enableSave = useAgentStore((state) => state.enableSave)
  const [isPolishing, setIsPolishing] = useState(false)
  // Create ref for AgentSettingList
  const agentSettingListRef = useRef<{ polishAllTexts: () => Promise<void> }>(null);

  // Expose methods to parent components
  useImperativeHandle(ref, () => ({
    polishAllTexts: async () => {
      if (agentSettingListRef.current) {
        setIsPolishing(true);
        await agentSettingListRef.current.polishAllTexts();
        setIsPolishing(false);
      }
    }
  }));

  // 控制按钮状态和文本
  const isNameValid = (agentEdit?.name?.length || 0) >= 2
  const isDisabled = !isNameValid || isPolishing || !enableSave
  const buttonText = agentEdit?.agentId ? '保存' : '创建'

  return (
    <View className="pb-118">
      <AgentCard></AgentCard>
      <View className="mb-12">
        <AgentContactCard></AgentContactCard>
      </View>
      <AgentSettingList ref={agentSettingListRef}></AgentSettingList>
      <View className="py-12">
        <AgentKnowledgeLib></AgentKnowledgeLib>
      </View>
      <BottomBar>
        <WemetaButton disabled={isDisabled} className="flex-1" onClick={save}>{buttonText}</WemetaButton>
      </BottomBar>
    </View>
  );
})
