import { useState } from "react";
import { View } from "@tarojs/components";

import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import WemetaInput from "@/components/wemeta-input/index";
import Taro, { nextTick, useUnload } from "@tarojs/taro";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";

type InputField = {
  id: string; // 唯一标识（用于 key）
  value: string;
  title: string;
};

export default function Index() {
  const agent = useAgentStore((state) => state.agentEdit);
  const { fetchAgent, saveAgent, updateEditAgent } = useAgentStoreActions();
  const questionGuides = agent?.questionGuides ?? [];
  const initialInputs: InputField[] = [
    { id: "1", value: "", title: "问题一" },
    { id: "2", value: "", title: "问题二" },
    { id: "3", value: "", title: "问题三" },
  ];

  questionGuides.map((q, index) => {
    initialInputs[index].value = q;
  });
  const [inputs, setInputs] = useState<InputField[]>(initialInputs);
  const handleChange = (id: string, newValue: string) => {
    setInputs((prev) =>{
      const r = prev.map((input) =>
        input.id === id ? { ...input, value: newValue } : input
      )
      return r
    });
  };
  let loading = false
  const handleSubmit = async () => {
    const r = {'questionGuides': inputs.map((item) => item.value).filter(item => item.length > 0)}
    if (!agent?.agentId) {
      updateEditAgent(r);
      Taro.navigateBack()
      return;
    }

    if(loading){
      return;
    }
    loading = true

    console.log(r)
    const result = await saveAgent(r);
    loading = false
    if (result) {
      await fetchAgent(agent.agentId);
      Taro.navigateBack();
    }
  };

  return (
    <PageCustom>
      <NavBarNormal backText="开场提问引导"></NavBarNormal>
      <View className="flex flex-col items-center w-full gap-16 p-16">
        {inputs.map((item) => {
          return (
            <View className="flex flex-col gap-6 w-full">
              <View className="text-14 font-medium text-black leading-28">
                {item.title}
              </View>
              <WemetaInput
                value={item.value}
                onInput={(value: string) => handleChange(item.id, value)}
                placeholder="请输入"
                maxlength={50}
              />
            </View>
          );
        })}
      </View>
      <View className="bottom-bar">
        <View className="pt-12 px-20">
          <View
            className={`button-rounded button-primary`}
            onClick={handleSubmit}
          >
            保存
          </View>
        </View>
      </View>
    </PageCustom>
  );
}
