import { useQueryClient } from '@tanstack/vue-query';
import { isNil } from 'lodash';
import { useQuasar } from 'quasar';
import AppNotificationDialog from 'src/components/dialogs/AppNotificationDialog.vue';
import { notifyError } from 'src/helpers';
import { CaptacionManagerActionCode } from 'src/models';
import { useCaptacionLite } from 'src/widgets/useStoreLite';
import { computed, ref } from 'vue';
import { useStore } from 'vuex';

export function useCaptacionActions() {
  const { dialog } = useQuasar();
  const { data } = useCaptacionLite();
  const idCaptacion = computed(() => data.value.ID_CAPTACION || null);
  const store = useStore();
  const cancelButton = (label = 'Cancelar') => ({
    label,
    fn: () => {},
  });
  const queryClient = useQueryClient();
  const actionInProgress = ref(false);
  const wrapAction: (action: () => Promise<any>) => Promise<void> = async (action) => {
    actionInProgress.value = true;
    store.commit('captacion/setLoading', true);
    await action();
    await queryClient.invalidateQueries({ queryKey: ['captacion', idCaptacion.value] });
    store.commit('captacion/setLoading', false);
    actionInProgress.value = false;
  };

  const confirmationMessage = (action: string) => `¿Seguro que quieres ${action} esta solicitud?`;
  function buildNotificationData(action: CaptacionManagerActionCode, actionLabel?: string, _id?: number) {
    const id = isNil(_id) ? idCaptacion.value : _id;
    if (!id) throw new Error('No se ha proporcionado un id de captación');

    switch (action) {
      case 'anular':
        return {
          title: 'Descartar solicitud',
          message: confirmationMessage('descartar'),
          actions: [
            cancelButton(),
            {
              label: 'Descartar solicitud',
              fn: () =>
                wrapAction(() =>
                  store.dispatch('captacion/anularCaptacion', { id }).then(() =>
                    dialog({
                      component: AppNotificationDialog,
                      componentProps: {
                        data: {
                          title: '¡Solicitud descartada!',
                          timer: 1500,
                        },
                      },
                    })
                  )
                ),
            },
          ],
        };
      case 'eliminar':
        return {
          title: 'Descartar solicitud definitivamente',
          message: confirmationMessage('eliminar'),
          actions: [
            cancelButton(),
            {
              label: 'Descartar solicitud definitivamente',
              fn: () =>
                wrapAction(() =>
                  store.dispatch('captacion/eliminar', { id }).then(() =>
                    dialog({
                      component: AppNotificationDialog,
                      componentProps: {
                        data: {
                          title: '¡Solicitud descartada definitivamente!',
                          timer: 1500,
                        },
                      },
                    })
                  )
                ),
            },
          ],
        };
      case 'preaprobar':
        return {
          title: `${actionLabel || 'Pre aprobar'} solicitud`,
          message: confirmationMessage(actionLabel || 'pre aprobar'),
          actions: [
            cancelButton(),
            {
              label: 'Confirmar',
              fn: () => wrapAction(() => store.dispatch('captacion/preAprobarCaptacion', id)),
            },
          ],
        };
      case 'aprobar':
        return {
          title: `${actionLabel || 'Aprobar'} solicitud`,
          message: confirmationMessage(actionLabel || 'aprobar'),
          actions: [
            cancelButton(),
            {
              label: 'Confirmar',
              fn: () => wrapAction(() => store.dispatch('captacion/aprobarCaptacion', id)),
            },
          ],
        };
      case 'restablecer':
        return {
          title: 'Restablecer solicitud',
          message: confirmationMessage('restablecer'),
          actions: [
            cancelButton(),
            {
              label: 'Confirmar',
              fn: () =>
                wrapAction(() =>
                  store.dispatch('captacion/restablecerCaptacion', id).then(() =>
                    dialog({
                      component: AppNotificationDialog,
                      componentProps: {
                        data: {
                          title: '¡Solicitud restablecida!',
                          timer: 1500,
                        },
                      },
                    })
                  )
                ),
            },
          ],
        };
      case 'finalizar':
        return {
          title: `${actionLabel || 'Finalizar'}  solicitud`,
          message: confirmationMessage(actionLabel || 'finalizar'),
          actions: [
            cancelButton(),
            {
              label: 'Confirmar',
              fn: async () =>
                wrapAction(() =>
                  store
                    .dispatch('captacion/finalizarCaptacion', id)
                    .then(() =>
                      dialog({
                        component: AppNotificationDialog,
                        componentProps: {
                          data: {
                            title: `¡Solicitud tramitada!`,
                            timer: 1500,
                          },
                        },
                      })
                    )
                    .catch((error) => {
                      notifyError(error, 'Error al finalizar la solicitud');
                    })
                ),
            },
          ],
        };
      case 'aceptar_y_finalizar':
        return {
          title: 'Aceptar la solicitud',
          message: confirmationMessage('Aceptar'),
          actions: [
            cancelButton(),
            {
              label: 'Confirmar',
              fn: async () => wrapAction(() => store.dispatch('captacion/finalizarCaptacion', id)),
            },
          ],
        };
      case 'confirmar':
        return {
          title: 'Confirmar solicitud',
          message: confirmationMessage('confirmar'),
          actions: [
            cancelButton(),
            {
              label: 'Confirmar',
              fn: async () => wrapAction(() => store.dispatch('captacion/confirmarCaptacion', id)),
            },
          ],
        };
      case 'dar_alta_usuario':
        break;
    }
    return null;
  }

  function showActionDialog(action: CaptacionManagerActionCode, actionLabel?: string, id?: number) {
    const data = buildNotificationData(action, actionLabel, id);
    if (!data) return;
    dialog({
      component: AppNotificationDialog,
      componentProps: {
        data,
      },
    });
  }

  return { showActionDialog, actionInProgress };
}
