import { clearCart, selectCart } from "features/order/orderSlice";
import { useCallback } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useCreateOrderMutation } from "redux/api/others";
import { useAppDispatch, useAppSelector } from "redux/hooks";
import { Customer } from "../../otp/types";

export default function useOrder() {
  const dispatch = useAppDispatch();
  const router = useNavigate();
  const { id } = useParams();
  const restaurantID = localStorage.getItem("restaurantID");
  const { mobilenumber, user_uuid } = JSON.parse(
    localStorage.getItem("customer") || "{}"
  ) as Customer;
  const { items, coupon, tip, tables, specialRequest } =
    useAppSelector(selectCart);

  const [createOrder] = useCreateOrderMutation();

  const handleCreateOrder = useCallback(() => {
    createOrder({
      phone: mobilenumber,
      couponID: coupon,
      discountAmount: 0,
      comment: specialRequest,
      timeslot: "",
      table_id: tables,
      deliveryType: "table",
      type: "table-pickup",
      user_id: id,
      restorant_id: restaurantID,
      items: items.map((i) => ({
        ...i,
        qty: i.quantity,
      })),
      office_no: "",
      vatvalue: 0,
      discountGiftCode: "",
      paymentType: "cod",
      uuid: user_uuid,
      pickup_comments: "",
      pickup_time: "",
      delivery_pickup_interval: "",
      orderPrice: items.reduce(
        (acc, item) => acc + item.price * item.quantity,
        0
      ),
      useWallet: 0,
      tip,
    })
      .then(() => {
        dispatch(clearCart());
        router(`/${id}/order`);
      })
      .catch((error) => {
        console.error("Create Order failed:", error);
      });
  }, [
    createOrder,
    mobilenumber,
    coupon,
    specialRequest,
    tables,
    id,
    restaurantID,
    items,
    user_uuid,
    tip,
    dispatch,
    router,
  ]);
  return { handleCreateOrder };
}
