import Taro, { useRouter } from "@tarojs/taro";
import { useState } from "react";
import { useAgentStore } from "@/store/agentStore";
import { TAgentDetail } from "@/types/agent";

const useEditContactCard = (
  editKey: string,
  initValue?: string | null,
  _agent?: TAgentDetail
) => {
  const agent = useAgentStore((state) => _agent ?? state.agent);
  const agentContactCard = useAgentStore((state) => state.agentContactCard);
  const [value, setValue] = useState(initValue ?? "");
  const { editAgentCard,fetchAgent } = useAgentStore();
  const handleSubmit = async () => {
    submit(value)
  };
  const submit = async (_value: string, navBack: boolean = true) => {
    if (!agent?.agentId) {
      return;
    }
    if (_value === undefined) {
      return;
    }

    
    // const prev = pickNonEmpty(agentContactCard??{})

    const result = await editAgentCard(agent.agentId, {
      ...agentContactCard,
      [editKey]: _value,
    });
    if(result){
      await fetchAgent(agent.agentId)
      navBack && Taro.navigateBack()
    }
  }
  const onChange = (e: any) => {
    setValue(e);
  };
  return {
    value,
    setValue,
    onChange,
    submit,
    handleSubmit,
  };
};

export default useEditContactCard;
