import { useDispatch, useSelector } from "react-redux";

import type { TypedUseSelectorHook } from "react-redux";

import { ItemType, OrderType } from "pages/pos/orders/types";
import { TableType } from "pages/pos/tables/types";
import { useEffect, useMemo, useState } from "react";
import { parseTranslations } from "utils/helpers";
import type { AppDispatch, RootState } from "./store";

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

export const useDebouncedValue = (value: any, delay: number = 500) => {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler: NodeJS.Timeout = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
};

export const useExtractTableItems = (table?: TableType) => {
  return useMemo(() => {
    let items: Array<ItemType> = [];
    let quantity: number = 0;
    table?.active_reservation?.orders?.forEach((order: OrderType) => {
      items = [...items, ...(order?.items || [])];
      quantity += Number(order?.quantities) || 0;
    });

    items = items.filter((i) => i.quantity > 0);
    items = [...removeDuplicatesAndIncreaseQuantity(items)];
    items = items.map((i: any) => ({ ...i, ...parseTranslations(i.product) }));
    return { items, quantity };
  }, [table]);
};

export function removeDuplicatesAndIncreaseQuantity(items: any[]) {
  const result: any[] = [];

  // Group objects by ID
  const grouped = items.reduce((acc, item) => {
    if (!acc[item.product.id]) {
      acc[item.product.id] = { ...item };
    } else {
      acc[item.product.id].quantity += item.quantity;
      acc[item.product.id].total_amount =
        acc[item.product.id]?.quantity * acc[item.product.id]?.unit_price;
    }
    return acc;
  }, {});

  // Convert grouped objects back to array
  Object.values(grouped).forEach((item) => result.push(item));
  return result;
}
