import { UserTypes } from "@/Constant/enums";
import React, { useEffect, useRef } from "react";

interface ModalProps {
  onClose: () => void;
  orderLength?: number;
}

const OrderSuccessModal: React.FC<ModalProps> = ({ onClose, orderLength }) => {
  const modalRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      // Check if the click is on the modal backdrop (outside the modal content)
      const target = event.target as HTMLElement;
      if (
        target.classList.contains("modal-backdrop") ||
        (modalRef.current && !modalRef.current.contains(target))
      ) {
        // First close the modal
        if (onClose) {
          onClose();
        }
        // Then redirect
        window.location.href = "/my-orders?_=in_progress";
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [onClose]);

  // Function to handle the download click
  const handleDownloadClick = (e: React.MouseEvent) => {
    // Prevent the default anchor link behavior
    e.preventDefault();

    // Open a new tab and navigate to /address-print
    const newTab = orderLength ? window.open(`/address-print?len=${orderLength}`, "_blank") : window.open(`/address-print`, "_blank");

    // Redirect the current tab to /my-orders
    window.location.href = "/my-orders?_=in_progress";

    // Focus on the newly opened tab (optional, but helpful)
    if (newTab) {
      newTab.focus();
    }
  };
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  return (
    <>
      <div ref={modalRef} className="modal-content">
        <h1 className="text-center mt-4">
          <i className="fa fa-3x fa-check-circle scale-box color-green2 shadow-xl rounded-circle" />
        </h1>
        <h2 className="text-center mt-3 font-700">
          Order placed successfully.
        </h2>
        {allData?.userType?.id === UserTypes.NormalCustomer ? (
          <p className="boxed-text-l opacity-80 mb-2 text-danger">
          Payment will be collected by the delivery person when the package is picked up.
          </p>
        ) : ''}
        <p className="boxed-text-l opacity-80 mb-2">
          You can download all addresses in this order.
        </p>
        <a
          href="/address-print"
          onClick={handleDownloadClick}
          className="close-menu btn btn-m btn-center-l button-s shadow-l rounded-s text-uppercase font-600 bg-blue-dark color-white mb-3"
        >
          <i className="fa fa-download" />
          &nbsp;Print&nbsp;Address
        </a>
      </div>
    </>
  );
};

export default OrderSuccessModal;
