import { useFetch } from '@win2win/shared-ui';
import { mapKeys } from 'lodash';
import { computed } from 'vue';
import { LOCATION_FIELDS } from '../const/location';

export function useHipoteca(idPedido: number) {
  const id = computed(() => idPedido);
  const key = computed(() => ['pedido', idPedido, 'producto', 'simulacion']);
  const query = computed(() => `w2w-query/pedido(${id.value})->ped_producto->producto(id=ped_producto.id_producto)->gama(id=producto.id_gama)`);
  const { data, fetching } = useFetch<any>(key, query, {
    pedido: ['id'],
    ped_producto: ['id', 'props'],
    producto: ['id', 'nombre'],
    gama: ['id', 'props'],
  });
  const productoProps = computed(() => mapKeys(data.value?.ped_producto?.props || {}, (_, k) => k.toLowerCase()));

  const keyUbicacion = computed(() => ['captacion', id.value || null, 'ubicacion', 'zona']);
  const queryUbicacion = computed(() => `w2w-query/ubicacion(id_pedido=${id.value})->zona(id=ubicacion.id_zona)`);
  const { data: ubicacion, fetching: fetchingUbicacion } = useFetch<any>(keyUbicacion, queryUbicacion, {
    ubicacion: LOCATION_FIELDS,
    zona: ['id', 'props'],
  });

  const ahorro = computed(() => productoProps.value.ahorro || 0);

  const precioInmueble = computed(() => Number(productoProps.value.precio_inmueble || 0));
  const importeSolicitado = computed(() => precioInmueble.value + totalCost.value - ahorro.value);
  const itp = computed(() => productoProps.value?.gastos?.itp || ubicacion.value?.zona?.props?.itp || 0);
  const ajd = computed(() => productoProps.value?.gastos?.ajd || ubicacion.value?.zona?.props?.ajd || 0);
  const itpImporte = computed(() => (itp.value ? (precioInmueble.value * itp.value) / 100 : 0));
  const ajdImporte = computed(() => (ajd.value ? (precioInmueble.value * ajd.value) / 100 : 0));
  const totalCost = computed(() => {
    return (
      Number(productoProps.value?.gastos?.notaria || 0) +
      Number(productoProps.value?.gastos?.registro_de_la_propiedad || 0) +
      Number(productoProps.value?.gastos?.gestoria || 0) +
      Number(productoProps.value?.gastos?.tasacion || 0) +
      itpImporte.value +
      ajdImporte.value
    );
  });

  return {
    fetching: fetching || fetchingUbicacion,
    totalCost,
    ahorro,
    importeSolicitado,
    itp,
    ajd,
    itpImporte,
    ajdImporte,
    precioInmueble,
    productoProps,
    ubicacion,
    gama: data.value?.ped_producto?.producto?.gama,
  };
}
