import { EstadoCaptacion, TipoCaptacion } from '@win2win/shared';
import { useQuasar } from 'quasar';
import { Tab } from 'src/components/common-ww/btns/tabs';
import AppNotificationDialog from 'src/components/dialogs/AppNotificationDialog.vue';
import { useCaptacionStore } from 'src/composables/useCaptacionStore';
import { Archivos, ArchivosESTADO_APROBACION, TieESTADO } from 'src/models';
import { captacionHipotecaTabs, captacionProductTabs, captacionUsuarioTabs, ESTADOS_CAPTACION } from 'src/pages/captaciones/consts';
import CaptacionBudgetDetailDialog from 'src/pages/captaciones/cotizacion/CaptacionBudgetDetailDialog.vue';
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { useAuth } from './useAuth';

export const formatIdCaptacion = (id: number) => (id === null ? '' : String(id).padStart(6, '0'));

export function useCaptacionPage() {
  const {
    data: captacion,
    loading,
    holderFiles,
    product,
    productFiles,
    getContactFullName,
    holders,
    contacts,
    id,
    incidents,
    ties,
    bankAccounts,
    activeIncidents,
    refreshCaptacion,
    budgets,
    props,
  } = useCaptacionStore();

  const store = useStore();
  const router = useRouter();
  const route = useRoute();
  const token = computed(() => route.params?.token || '');
  const idCaptacion = computed(() => route.params?.ID_CAPTACION || '');
  const currentTab = computed(() => router.currentRoute.value.path.split('/').pop() || '');
  const { isProveedor, isAdmin } = useAuth();

  const load = () => store.commit('captacion/setLoading', true);
  const stopLoad = () => store.commit('captacion/setLoading', false);

  const stateIndicator = computed(() => {
    const index = ESTADOS_CAPTACION.findIndex((s) => s.value === captacion.value.ESTADO);
    return {
      label: ESTADOS_CAPTACION[index].label,
      color: ESTADOS_CAPTACION[index].color,
    };
  });

  const createIncidencia = async (payload) => {
    payload.ID_CAPTACION = id.value;
    payload.ID_PRODUCTO = product.value.ID_PRODUCTO;
    return await store.dispatch('captacion/tsCreateIncidencia', payload);
  };

  const allDocumentsUploaded = computed(() => false);
  const incidenciaEnDatosContacto = computed(() => false);
  const confirmDocumentsLoaded = () => alert('Confirmar documentacion');

  const getProductFileSubtitle = (file: Archivos): string => {
    let subtitle = '';
    if (file.ID_CONTACTO) {
      const contactIds = file.ID_CONTACTO.toString().split(',');
      for (const [index, id] of contactIds.entries()) {
        const contact = contacts.value.filter((contact) => contact.ID_CONTACTO === Number(id))[0];
        const suffix = contactIds.length === index + 1 ? '' : ', ';
        subtitle = subtitle + getContactFullName(contact) + suffix;
      }
    }
    return subtitle;
  };

  const holdersDocs = computed(() =>
    holderFiles.value.map((file) => ({
      ...file,
      title: file.CONTACTO_ARTICULO_ARCHIVO.NOMBRE,
      subtitle: getContactFullName(file.contact),
      categories: ['contacto'],
    }))
  );

  const productDocs = computed(() => {
    return productFiles.value.map((file) => {
      const categories = ['finca'];
      if (file.ID_CONTACTO) {
        categories.push('contacto');
      }
      return {
        ...file,
        title: file.R_ARCHIVOS_ARTICULO_DOCUMENTO?.DESCRIPCION || '',
        subtitle: getProductFileSubtitle(file),
        categories,
      };
    });
  });

  const documents = computed(() => holdersDocs.value.concat(productDocs.value as any[]));

  const tabs = computed(() => {
    let captacionTabs: any = [];
    if (!captacion.value) return [];

    if (captacion.value.TIPO == TipoCaptacion.PEDIDOS) {
      captacionTabs = captacionHipotecaTabs;
    }

    if (captacion.value.TIPO == TipoCaptacion.PRODUCTOS) {
      captacionTabs = captacionProductTabs;
    }

    if (captacion.value.TIPO == TipoCaptacion.USUARIOS) {
      captacionTabs = captacionUsuarioTabs;
    }

    return [...captacionTabs]
      .filter((tab) => {
        if (isAdmin.value) return true;

        if (tab.name === 'documents' && documents.value.length === 0) {
          return false;
        }

        if (tab.name === 'incidents' && incidents.value.length === 0) {
          return false;
        }

        if (tab.name === 'budget' && ties.value.length === 0) {
          return false;
        }

        if (tab.name === 'bank-account' && bankAccounts.value.length === 0) {
          return false;
        }

        if (tab.name === 'questions' && isProveedor) {
          return false;
        }

        if (tab.name === 'contract') {
          return false;
        }

        return true;
      })
      .map((tab) => {
        if (tab.name === 'documents') {
          const count = documents.value.filter((doc) => !doc.FECHA_SUBIDA).length;
          const countAdmin = documents.value.filter((doc) => !doc.FECHA_APROBADO && doc.FECHA_SUBIDA).length;
          return {
            ...tab,
            notifications: isAdmin.value ? countAdmin : count,
          };
        }

        if (tab.name === 'incidents') {
          return {
            ...tab,
            notifications: activeIncidents.value.length,
          };
        }
        if (tab.name === 'budget') {
          const pendingToGenerate = captacion.value.ESTADO == EstadoCaptacion.APROBADA && isAdmin.value ? '!' : 0;
          const pendingToAccept = ties.value.some((tie) => tie.ESTADO === TieESTADO.ACEPTADO) ? 0 : ties.value.filter((tie) => tie.ESTADO === TieESTADO.PUBLICADO).length;
          return {
            ...tab,
            notifications: pendingToGenerate || pendingToAccept,
          };
        }

        return tab;
      }) as Tab[];
  });

  const bankAccountsStateIndicatorLabels = ['Incidencia', 'Sin verificar', 'Verificada'];
  const bankAccountsStateIndicatorColors = ['red', 'grey', 'green'];
  const bankAccountsStateIndicator = computed(() => {
    const withIncidents = bankAccounts.value.filter((acc) => acc.VERIFICADA === '0').length > 0;
    const allVerify = bankAccounts.value.filter((acc) => acc.VERIFICADA === '1').length === bankAccounts.value.length && bankAccounts.value.filter((acc) => acc.VERIFICADA === '1').length > 0;

    let index = 1;
    if (withIncidents) {
      index = 0;
    }

    if (allVerify) {
      index = 2;
    }

    return {
      label: bankAccountsStateIndicatorLabels[index],
      color: bankAccountsStateIndicatorColors[index],
    };
  });

  const disablePreAprobar = computed(() => {
    const documentsVerify = documents.value.length > 0 && documents.value.every((document) => document.APROBADA === ArchivosESTADO_APROBACION.APROBADA);
    const holdersVerify = holders.value.length > 0;
    return !documentsVerify || !holdersVerify;
  });

  const { dialog } = useQuasar();

  const showBudgetDetails = (budget: any) =>
    dialog({
      component: CaptacionBudgetDetailDialog,
      componentProps: {
        budget,
      },
    });

  const checkDocumentsUploaded = () => {
    const allPendingToCheck = documents.value.every((document) => document.APROBADA === ArchivosESTADO_APROBACION.PENDIENTE_A_APROBAR);
    if (allPendingToCheck) {
      dialog({
        component: AppNotificationDialog,
        componentProps: {
          data: {
            timer: 3000,
            title: '¡Documentos subidos correctamente!',
          },
        },
      });
    }
  };
  const uploadFile = async (payload: FormData) => {
    await store.dispatch('contactos/tsUploadFile', payload);
    refreshCaptacion();
    checkDocumentsUploaded();
  };
  return {
    checkDocumentsUploaded,
    confirmDocumentsLoaded,
    uploadFile,
    disablePreAprobar,
    allDocumentsUploaded,
    incidenciaEnDatosContacto,
    currentTab,
    captacion,
    loading,
    token,
    idCaptacion,
    documents,
    stateIndicator,
    bankAccountsStateIndicator,
    tabs,
    ties,
    budgets,
    activeIncidents,
    refreshCaptacion,
    createIncidencia,
    load,
    stopLoad,
    showBudgetDetails,
    props,
  };
}
