import {useContextSection} from '@hooks';
import {context} from '../context';
import {useMemo} from 'react';
import {useQuery} from '@tanstack/react-query';
import {getReserveWarningScreenList} from '@apis';

export function usePieChartState() {
  const data = useContextSection(context, state => state[0]);

  const state = useMemo(
    function () {
      if (!data?.list) return [];

      return data.list.reduce<{name: string; value: number}[]>(function (
        pre,
        next,
      ) {
        const {wllbClass, arrivalNum} = next;

        if (!arrivalNum) return pre;

        const idx = pre.findIndex(val => val.name === wllbClass);
        if (idx >= 0) {
          pre[idx].value += Number(arrivalNum);
        } else {
          pre.push({name: wllbClass, value: Number(arrivalNum)});
        }

        return pre;
      },
      []);
    },
    [data],
  );

  return state;
}

export function useBarChartState() {
  const {data} = useQuery({
    queryKey: [getReserveWarningScreenList.name],
    async queryFn({signal}) {
      const data = await getReserveWarningScreenList(signal);

      if (data.msg === '200') {
        return data.data.list.map(function (val) {
          const name =
            val.materialName.length > 5
              ? val.materialName.slice(0, 5) + '...'
              : val.materialName;

          return {name, data: val.amount};
        });
      }

      return [];
    },
    initialData: [],
    refetchInterval: 1000 * 60 * 10,
  });

  return data;
}
