import { useMemo } from 'react';
import { useQuery } from 'react-query';

import { parseAsInteger, useQueryState } from 'nuqs';

import useSnackbar from '@material-hu/components/design-system/Snackbar';

import { payrollMobilityAdoKeys } from '../queries';
import { getPayrollReceipts } from '../services';

export const useGetPayrollReceipts = () => {
  const { enqueueSnackbar } = useSnackbar();
  const [selectedYear] = useQueryState('year', parseAsInteger);

  const { data: receipts = [], ...query } = useQuery({
    queryKey: payrollMobilityAdoKeys.list(),
    queryFn: getPayrollReceipts,
    select: response => response.data,
    onError: () => {
      enqueueSnackbar({
        title: 'No pudimos cargar tus nóminas. Intentá de nuevo más tarde.',
        variant: 'error',
      });
    },
  });

  const receiptYears = useMemo(
    () => [...new Set(receipts.map(r => r.ejercicio))].sort((a, b) => b - a),
    [receipts],
  );

  const receiptsFiltered = useMemo(() => {
    if (!selectedYear) return receipts;
    return receipts.filter(r => r.ejercicio === selectedYear);
  }, [receipts, selectedYear]);

  return { receipts: receiptsFiltered, receiptYears, ...query };
};
