import {addDictionaryData, editDictionaryData, getDictionaryInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {usePutData, useQueryDataInfo} from '@hooks';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';
import {useDicionaryType} from '../../hooks';
import {AddDictionaryListParams} from '@models';

type FormState = {
  dictionaryId: string;
  dictionaryName: string;
  dictionaryCode: string;
};

const validate = object({
  dictionaryId: string().required('请输入特来电ID'),
  dictionaryName: string().required('请输入名称'),
  dictionaryCode: string().required('请输入编号'),
});

export function useFormState({
  visible,
  id,
  onClose,
  onFetch,
}: {
  visible: boolean;
  id: string;
  onClose: () => void;
  onFetch: () => void;
}) {
  const formInstance = useForm<FormState>({
    defaultValues: {
      dictionaryCode: '',
      dictionaryId: '',
      dictionaryName: '',
    },
    resolver: yupResolver(validate),
  });

  const {clearErrors, handleSubmit} = formInstance;

  useEffect(
    function () {
      visible && clearErrors();
    },
    [clearErrors, visible],
  );

  const type = useDicionaryType();
  const [isLoading, {addMutate, editMutate}] = usePutData({
    addFn: addDictionaryData,
    editFn: editDictionaryData,
    onClose,
    onFetch,
  });
  const onSubmit = handleSubmit(function ({
    dictionaryCode,
    dictionaryId,
    dictionaryName,
  }) {
    const params: AddDictionaryListParams = {
      tldId: dictionaryId,
      code: dictionaryCode,
      name: dictionaryName,
      type,
    };

    id ? editMutate({id, ...params}) : addMutate(params);
  });

  return [{formInstance, isLoading}, {onSubmit}] as const;
}

export function useControl() {
  const {control} = useFormContext<FormState>();

  return control;
}

export function useWatchId(id: string) {
  const {setValue} = useFormContext<FormState>();
  const type = useDicionaryType();

  const data = useQueryDataInfo({
    queryFn: getDictionaryInfo,
    params: [type, id],
    enabled: Boolean(id),
  });

  useEffect(
    function () {
      setValue('dictionaryCode', data?.code ?? '');
      setValue('dictionaryId', data?.tldId ?? '');
      setValue('dictionaryName', data?.name ?? '');
    },
    [setValue, data],
  );
}
