import { getValue } from '@win2win/shared-ui';
import { keys } from 'lodash';
import { api } from 'src/boot/axios';
import { useAuth } from 'src/composables/useAuth';
import { useRefetch } from 'src/composables/useRefetch';
import { useRunAsyncTask } from 'src/composables/useRunAsyncTask';
import { useWidgetStore } from 'src/composables/useWidgetStore';
import { notifyError } from 'src/helpers';
import { LayoutContext } from 'src/models';
import { useCaptacionLite } from 'src/widgets/useStoreLite';
import { computed, MaybeRef, Ref } from 'vue';
import { z } from 'zod';
import { DynamicEvent } from '../useDynamicEvents';
import { getParsePayload } from './helpers';

export function useSharedEvents(context: MaybeRef<LayoutContext>, loading: Ref<boolean>) {
  const { isAdmin } = useAuth();
  const { id } = useCaptacionLite();
  const queryKey = computed(() => [getValue(context), id.value]);
  const refetch = useRefetch([{ queryKey }, { type: 'all' }]);
  const { getPropsFromStore } = useWidgetStore();
  const runAsyncTask = useRunAsyncTask(loading, () => refetch());

  const parsePayload = getParsePayload<SharedSchemas>(SHARED_EVENTS_SCHEMAS);

  const handleEvent = (event: DynamicEvent) => {
    event.payload = getPropsFromStore(event.payload);
    try {
      const { code } = event;
      // PUBLIC ACTIONS

      if (code === 'add_image') {
        const data = parsePayload<typeof code>(event);
        const acceptVideo = !!data.acceptVideo;
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = `image/*${acceptVideo ? ',video/*' : ''}`;
        input.onchange = async (e) => {
          const file = (e.target as HTMLInputElement).files?.[0];
          if (!file) return;
          const formData = new FormData();
          formData.append('file', file);
          if (data.idCaptacion) {
            formData.append('ID_CAPTACION', String(data.idCaptacion));
          }
          if (data.idContacto) {
            formData.append('ID_CONTACTO', String(data.idContacto));
          }
          if (data.idPartner) {
            formData.append('ID_PARTNER', String(data.idPartner));
          }
          if (data.idProducto) {
            formData.append('ID_PRODUCTO', String(data.idProducto));
          }
          const filetype = getFileType(file);
          formData.append('FILETYPE', filetype);
          if (data.idTipoDocumento) {
            formData.append('ID_TIPO_DOCUMENTO', String(data.idTipoDocumento));
          }
          runAsyncTask(() => api.post('/files', formData), { successMessage: 'Imagen subida correctamente' });
        };
        input.click();
        return;
      }

      // ADMIN ACTIONS
      if (!isAdmin.value) return;
    } catch (error) {
      console.error('Error handling captacion event:', error);
      notifyError(error);
    }
  };
  return handleEvent;
}

const SHARED_EVENTS_SCHEMAS = {
  add_image: z.object({
    idCaptacion: z.number().optional(),
    idContacto: z.number().optional(),
    idPartner: z.number().optional(),
    idProducto: z.number().optional(),
    idTipoDocumento: z.number().optional(),
    acceptVideo: z.boolean().optional(),
    showSignable: z.boolean().optional().default(false),
  }),
} as const;
type SharedSchemas = typeof SHARED_EVENTS_SCHEMAS;
export const SHARED_EVENTS = keys(SHARED_EVENTS_SCHEMAS);

const getFileType = (file: File) => {
  const fileType = file.type.split('/')[0];
  return fileType === 'image' || fileType === 'video' ? fileType : 'document';
};
