import { message } from "antd";
import {
  clearCart,
  selectCart,
  selectGrandTotal,
  selectHighestPricedLoyaltyItem,
} from "features/order/orderSlice";
import { OrderType } from "pages/checkout/hooks/types.ts";
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 { subdomain } = 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,
    location,
    discount,
    plateCar,
    pickupTime,
    pickupDate,
    pickupType,
  } = useAppSelector(selectCart);
  const highestLoyaltyItem = useAppSelector(selectHighestPricedLoyaltyItem);
  const { useLoyaltyPoints } = useAppSelector(selectCart);

  const orderPrice = useAppSelector(selectGrandTotal);

  const [createOrder] = useCreateOrderMutation();

  const getDeliveryMethod = useCallback(() => {
    if (orderType === OrderType.Delivery) return 1;
    if (orderType === OrderType.Pickup) return 2;
    if (orderType === OrderType.DineIn) return 3;
    if (orderType === OrderType.Gift) return 10;
    if (orderType === OrderType.ScheduledOrder) return 9;
    if (orderType === OrderType.ToRoom) return 5;
    if (orderType === OrderType.ToOffice) return 4;
    return undefined;
  }, [orderType]);

  const handleCreateOrder = useCallback(() => {
    createOrder({
      phone: mobilenumber || phone || giftDetails?.senderPhone,
      comment: specialRequest,
      delivery_method: getDeliveryMethod(),
      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?.map((e) => e.id) || [],
        extrasgroup: i.extrasgroup || [],
        order_item_comment: i.comment || "",
        variant: i.variant?.id || "",
      })),
      office_no: officeDetails?.officeNo || "",
      vatvalue: 0,
      ...(discount.isDiscount ? { couponID: coupon } : {}),
      ...(discount.isGift ? { discountGiftCode: coupon } : {}),
      discountAmount: discount.value || 0,
      paymentType: "cod",
      uuid: user_uuid,
      pickup_comments: "",
      pickup_time: pickupTime,
      pickup_date: pickupDate,
      car_plate: plateCar,
      pickupTimeType: pickupType,
      delivery_pickup_interval: "",
      orderPrice: orderPrice,
      use_loylaty: useLoyaltyPoints && highestLoyaltyItem ? 1 : 0,
      useWallet: 0,
      tip,
      userCoordinates:
        location?.lat && location?.lng
          ? `${location?.lat},${location?.lng}`
          : "",
      delivery_address: location?.address,
      ...(orderType === 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: unknown) => {
        const mutationResult = res as {
          data?: { result?: { orderID?: string } };
          error?: { data?: { message?: string } };
        };
        if (mutationResult.error)
          message.error(
            mutationResult.error.data?.message || t("order.createOrderFailed"),
          );
        else {
          const redirectMessageKey = "order-redirect-loader";
          if (orderType === OrderType.Gift && mutationResult.data?.result?.orderID) {
            message.loading({
              content: t("order.redirectingToPayment", {
                defaultValue: "Redirecting to payment...",
              }),
              key: redirectMessageKey,
              duration: 0,
            });
            window.location.href = `${PAYMENT_CONFIRMATION_URL}/${mutationResult.data.result.orderID}`;
          } else {
            message.destroy(redirectMessageKey);
            if (mutationResult.data?.result?.orderID) {
              navigate(`/${subdomain}/order/${mutationResult.data.result.orderID}`);
            }
          }
          dispatch(clearCart());
          if (mutationResult.data?.result?.orderID) {
            localStorage.setItem("orderID", mutationResult.data.result.orderID);
          }
        }
      })
      .catch((error: unknown) => {
        console.error("Create Order failed:", error);
      });
  }, [
    createOrder,
    mobilenumber,
    phone,
    giftDetails?.senderPhone,
    giftDetails?.receiverName,
    giftDetails?.receiverPhone,
    giftDetails?.message,
    giftDetails?.isSecret,
    giftDetails?.senderEmail,
    giftDetails?.senderName,
    specialRequest,
    getDeliveryMethod,
    tables,
    orderType,
    restaurantID,
    items,
    officeDetails?.officeNo,
    discount.isDiscount,
    discount.isGift,
    discount.value,
    coupon,
    user_uuid,
    estimateTime,
    orderPrice,
    useLoyaltyPoints,
    highestLoyaltyItem,
    tip,
    location?.lat,
    location?.lng,
    location?.address,
    t,
    navigate,
    subdomain,
    dispatch,
  ]);
  return { handleCreateOrder };
}
