import { FilterQueryParams } from '@win2win/shared';
import { uniqueId } from 'lodash';
import { ProductoESTADO } from 'src/models';
import { product_states } from 'src/pages/productos/consts';
import { computed, onMounted, ref, watch } from 'vue';
import { fetchUniq } from './fetching/fetchUniq';

export interface ProductStat {
  state: ProductoESTADO | 99;
  count: number;
}

export function useProductosStats(filters: FilterQueryParams) {
  const rawStats = ref<ProductStat[]>([]);
  const fetchingStats = ref(false);
  const stats = computed(() => {
    return rawStats.value.map((stat) => {
      const productState = product_states.filter(({ state }) => state == stat.state)[0];
      if (productState) {
        return {
          label: productState.label,
          color: productState.color,
          count: stat.count,
          value: stat.state,
        } as any;
      }
      return {
        label: '',
        color: '',
        count: stat.count,
        value: stat.state,
      } as any;
    });
  });

  const fetchStats = () => {
    fetchingStats.value = true;
    fetchUniq<ProductStat[]>('productos-stats', {}, uniqueId())
      .then((data) => (rawStats.value = data || []))
      .finally(() => (fetchingStats.value = false));
  };

  const statSelected = ref<Number[]>([99]);
  const toggleStat = ({ value }: any) => {
    let selected = [...statSelected.value];
    if (selected.includes(value)) {
      selected = selected.filter((item) => item !== value);
    } else if (value === 99) {
      selected = [99];
    } else {
      selected = selected.filter((item) => item !== 99);
      selected.push(value);
    }
    if (!selected.length) selected.push(99);
    statSelected.value = selected;
  };

  watch(statSelected, (value) => {
    filters['estado'] = value;
  });

  onMounted(() => fetchStats());

  return { stats, fetchingStats, statSelected, fetchStats, toggleStat };
}
