import { nextTick, onUnmounted, ref, unref, watch } from 'vue';
import { getDynamicProps } from '@/utils/zt';
import type { FormActionType, FormProps, FormSchema, UseFormReturnType } from '../types/form';

type Props = Partial<FormProps>;

export function useForm(props?: Props): UseFormReturnType {
  const formRef = ref<Nullable<FormActionType>>(null);
  const loadedRef = ref<Nullable<boolean>>(false);

  async function getForm() {
    const form = unref(formRef);

    if (!form) {
      console.error(
        'The form instance has not been obtained, please make sure that the form has been rendered when performing the form operation!'
      );
    }
    await nextTick();
    return form as FormActionType;
  }

  function register(instance: FormActionType) {
    onUnmounted(() => {
      formRef.value = null;
      loadedRef.value = null;
    });

    if (unref(loadedRef) && instance === unref(formRef)) return;

    formRef.value = instance;
    loadedRef.value = true;

    watch(
      () => props,
      () => {
        if (props) {
          instance.setFormProps(getDynamicProps(props));
        }
      },
      {
        immediate: true,
        deep: true
      }
    );
  }

  const methods: FormActionType = {
    updateSchema: async (data: Partial<FormSchema> | Partial<FormSchema>[]) => {
      const form = await getForm();
      form.updateSchema(data);
    },
    setFormProps: async (formProps: Partial<FormProps>) => {
      const form = await getForm();
      await form.setFormProps(formProps);
    },

    resetFields: async () => {
      getForm().then(async form => {
        await form.resetFields();
      });
    },

    clearValidate: async (name?: string | string[]) => {
      const form = await getForm();
      await form.clearValidate(name);
    },

    getFieldsValue: <T>() => {
      return unref(formRef)?.getFieldsValue() as T;
    },

    setFieldsValue: async <T extends Recordable<any>>(values: T) => {
      const form = await getForm();

      form.setFieldsValue(values);
    },

    submit: async (): Promise<any> => {
      const form = await getForm();
      return form.submit();
    },

    validate: async (nameList?: any[]): Promise<Recordable> => {
      const form = await getForm();
      return form.validate(nameList);
    },

    setLoading: (value: boolean) => {
      loadedRef.value = value;
    },

    setSchema: async values => {
      const form = await getForm();
      form.setSchema(values);
    },
    restoreValidation: async () => {
      const form = await getForm();
      form.restoreValidation();
    }
  };

  return [register, methods];
}
