import { useMemo, useState } from "react";

export const useOrder = () => {
  const [order, setOrder] = useState<{ name: string; price: number; quantity: number }[]>([]);

  const toggleItem = (name: string, price: number) => {
    setOrder((prev) => {
      const existing = prev.find((o) => o.name === name);
      if (existing) return prev.filter((o) => o.name !== name);
      return [...prev, { name, price, quantity: 1 }];
    });
  };

  /**
   * en vez de toggleItem(...)
   * addItem(name: string, price: number)  // suma 1
   * removeOne(name: string)               // resta 1
   * getQuantity(name: string)             // para pintar badge
   */

  // Add +1 unit of a product
  const addItem = (name: string, price: number) => {
    setOrder((prev) => {
      const existing = prev.find((i) => i.name === name);
      if (!existing) {
        return [...prev, { name, price, quantity: 1 }];
      }
      return prev.map((i) =>
        i.name === name ? { ...i, quantity: i.quantity + 1 } : i
      );
    });
  };

  // Remove -1 unit of a product
  const removeOne = (name: string) => {
    setOrder((prev) => {
      const existing = prev.find((i) => i.name === name);
      if (!existing) return prev;

      if (existing.quantity <= 1) {
        return prev.filter((i) => i.name !== name);
      }

      return prev.map((i) =>
        i.name === name ? { ...i, quantity: i.quantity - 1 } : i
      );
    });
  };

  // Get quantity of a product in the order
  const getQuantity = (name: string): number =>
    order.find((i) => i.name === name)?.quantity ?? 0;

  // Optional: remove line completely
  const removeItem = (name: string) => {
    setOrder((prev) => prev.filter((i) => i.name !== name));
  };

  // Total
  const total = useMemo(
    () => order.reduce((sum, item) => sum + item.price * item.quantity, 0),
    [order]
  );

  const adjustQuantity = (itemName: string, delta: number) => {
    setOrder((prev) =>
      prev
        .map((o) =>
          o.name === itemName ? { ...o, quantity: o.quantity + delta } : o
        )
        .filter((o) => o.quantity > 0)
    );
  };

  return { order, addItem, removeOne, getQuantity, removeItem, toggleItem, adjustQuantity, total };
};

export default useOrder;
