import { mapKeys, orderBy, snakeCase } from 'lodash';
import moment from 'moment';
import { toEUR } from 'src/helpers/formatters';
import { Captacion, Contacto, CuentaBancaria, Notification } from 'src/models';
import { PropsHipoteca } from 'src/pages/captaciones/_hipoteca/props-hipoteca';
import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
import { useProductStore } from './useProductStore';

export function useCaptacionStore() {
  const getContactFullName = (contact: Contacto) => {
    if (!contact) return '';
    const { NOMBRE, APELLIDO, APELLIDO2 } = contact;
    return `${NOMBRE} ${APELLIDO || ''} ${APELLIDO2 || ''}`.trim();
  };

  const store = useStore();
  const route = useRoute();
  // const fetchPath = computed(() => `captacion_estudios/${route.params?.ID_CAPTACION || ''}`);
  // const queryKey = computed(() => ['captacion', route.params?.ID_CAPTACION as string]);
  // const { data: captacion, fetching, invalidate } = useFetch<any>(queryKey, fetchPath);

  const notifications = computed<Notification[]>(() => store.getters['captacion/notifications']);
  const loadingNotifications = computed<boolean>(() => store.getters['captacion/loadingNotifications']);
  const data = computed<Captacion>(() => store.getters['captacion/data']);
  const token = computed<string | null>(() => store.getters['captacion/token']);
  const loading = computed<boolean>(() => store.getters['captacion/loading']);
  const id = computed<number | null>(() => data.value?.ID_CAPTACION || null);
  const contactId = computed<number>(() => data.value?.CONTACTO?.ID_CONTACTO);
  const contact = computed<Contacto>(() => data.value?.CONTACTO);
  const documents = computed(() => data.value?.CONTACTO.DOCUMENTOS || []);
  const ties = computed(() => orderBy(data.value?.TIES, 'FECHA_UPD') || []);
  const bankAccounts = computed<CuentaBancaria[]>(() => store.getters['captacion/bankAccounts']);
  const documentFilter = computed(() => store.getters['captacion/documentFilter']);
  const props = computed(() => mapKeys(data.value?.PRODUCTOS_PEDIDO?.[0]?.PROPS || {}, (_, k) => snakeCase(k)) as PropsHipoteca);

  const { product, productLocation, productFiles, productProps, holders, contacts, countryId, incidents, activeIncidents, productId } = useProductStore();

  const holderFiles = computed(() =>
    holders.value.flatMap(
      (obj) =>
        obj.CONTACTO_ARTICULO?.CONTACTO_ARTICULO_ARCHIVOS?.map((file) => ({
          ...file,
          contactName: getContactFullName(obj.CONTACTO_ARTICULO),
          contactId: obj.CONTACTO_ARTICULO.ID_CONTACTO,
          contact: obj.CONTACTO_ARTICULO,
        })) || []
    )
  );

  const budgets = computed(() =>
    orderBy(ties.value, 'FECHA_CREADO', 'asc').map((tie, i) => ({
      title: `Cotización ${('0' + (i + 1)).slice(-2)}`,
      date: moment(tie.FECHA_CREADO).format('DD/MM/YYYY'),
      budgetProps: [
        { label: 'Hectáreas de cultivo', value: `${tie.ANALISIS.SUPERFICIE_CULTIVABLE} há` },
        { label: 'Precio por hectárea', value: toEUR(tie.ANALISIS.UNITARIO_ANUAL) + '/há' },
        { label: 'Duración del contrato', value: tie.ANALISIS.ANIOS + ' años' },
        { label: 'Previsión cuota del alquiler', value: toEUR(tie.ANALISIS.TOTAL_ANUAL) + '/año' },
      ],
      showingMore: false,
      tie,
    }))
  );

  const contactIsHolder = computed(() => holders.value.some((holder) => holder.CONTACTO_ARTICULO.ID_CONTACTO === contactId.value));
  const refreshCaptacion = () => {};

  return {
    data,
    notifications,
    loading,
    loadingNotifications,
    id,
    token,
    holderFiles,
    product,
    contacts,
    holders,
    contactIsHolder,
    contactId,
    contact,
    productLocation,
    productProps,
    productFiles,
    ties,
    countryId,
    documents,
    bankAccounts,
    documentFilter,
    incidents,
    activeIncidents,
    budgets,
    productId,
    props,
    getContactFullName,
    refreshCaptacion,
  };
}
