import { message } from "antd";
import {
  clearCart,
  selectCart,
  selectCartTotalWithLoyaltyDiscount,
  selectHighestPricedLoyaltyItem,
} from "features/order/orderSlice";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { useCreateOrderMutation } from "redux/api/others";
import { useAppDispatch, useAppSelector } from "redux/hooks";
import { PAYMENT_CONFIRMATION_URL } from "utils/constants";
import { Customer } from "../../otp/types";

export default function useOrder() {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const { t } = useTranslation();
  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,
    phone,
    estimateTime,
    officeDetails,
    orderType,
    giftDetails,
  } = useAppSelector(selectCart);
  const highestLoyaltyItem = useAppSelector(selectHighestPricedLoyaltyItem);
  const { useLoyaltyPoints } = useAppSelector(selectCart);

  const orderPrice = useAppSelector(selectCartTotalWithLoyaltyDiscount);

  const [createOrder] = useCreateOrderMutation();

  const handleCreateOrder = useCallback(() => {
    createOrder({
      phone: mobilenumber || phone || giftDetails?.senderPhone,
      couponID: coupon,
      discountAmount: 0,
      comment: specialRequest,
      delivery_method: "3",
      timeslot: "",
      table_id: tables[0],
      deliveryType: orderType,
      type: "table-pickup",
      // user_id: id,
      restorant_id: restaurantID,
      items: items.map((i) => ({
        ...i,
        qty: i.quantity,
        extras: i.extras || [],
        extrasgroup: i.extrasgroup || [],
      })),
      office_no: officeDetails?.officeNo || "",
      vatvalue: 0,
      discountGiftCode: "",
      paymentType: "cod",
      uuid: user_uuid,
      pickup_comments: "",
      pickup_time: estimateTime,
      delivery_pickup_interval: "",
      orderPrice: orderPrice,
      use_loylaty: useLoyaltyPoints && highestLoyaltyItem ? 1 : 0,
      useWallet: 0,
      tip,
      ...(orderType === "gift"
        ? {
            receiverName: giftDetails?.receiverName,
            receiverPhone: giftDetails?.receiverPhone,
            specialMessage: giftDetails?.message,
            keepNameSecret: giftDetails?.isSecret,
            senderEmail: giftDetails?.senderEmail,
            senderPhone: giftDetails?.senderPhone,
            senderName: giftDetails?.senderName,
            dineType: orderType,
          }
        : {}),
    })
      .then((res: any) => {
        if (res.error)
          message.error(res.error.data.message || t("order.createOrderFailed"));
        else {
          if (orderType === "gift")
            // navigate(`/${PAYMENT_CONFIRMATION_URL}/${res.data.result.orderID}`, {
            //   replace: false,
            // });
            window.location.href = `${PAYMENT_CONFIRMATION_URL}/${res.data.result.orderID}`;
          // window.open(
          //   `${PAYMENT_CONFIRMATION_URL}/${res.data.result.orderID}`,
          // );
          else navigate(`/${id}/order/${res.data.result.orderID}`);
          dispatch(clearCart());
          localStorage.setItem("orderID", res.data.result.orderID);
        }
      })
      .catch((error: any) => {
        console.error("Create Order failed:", error);
      });
  }, [
    createOrder,
    mobilenumber,
    phone,
    giftDetails?.senderPhone,
    giftDetails?.receiverName,
    giftDetails?.receiverPhone,
    giftDetails?.message,
    giftDetails?.isSecret,
    giftDetails?.senderEmail,
    giftDetails?.senderName,
    coupon,
    specialRequest,
    tables,
    orderType,
    id,
    restaurantID,
    items,
    officeDetails?.officeNo,
    user_uuid,
    estimateTime,
    tip,
    orderPrice,
    t,
    navigate,
    dispatch,
  ]);
  return { handleCreateOrder };
}
