import React, { useEffect, useState } from "react";
import "./Receiver_info_holder.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faLocationDot, faPhone } from "@fortawesome/free-solid-svg-icons";
import Cancel_Order_btn from "../../../common-components/common_btn/cancel_Order_btn/Cancel_Order_btn";

import { encodeId } from "../../../../utils/common";
import { appSetup } from "../../../../features/master/masterSlice";
import { useDispatch, useSelector } from "react-redux";
import { useRouter } from "next/navigation";

function Receiver_info_holder({ order }) {
  const navigate = useRouter();

  const handleClick = (id) => {
    navigate.push(`/cancel-order/${encodeId(id)}`);
  };
  const handleClickReturn = (id) => {
    navigate.push(`/return-order/${encodeId(id)}`);
  };

  const dispatch = useDispatch();
  const appSetupdata = useSelector((state) => state.master.app_setup);
  // useEffect(() => {
  //   // Ensure ID is valid before dispatching
  //   dispatch(appSetup());
  // }, [dispatch]);

  const [errorMessage, setErrorMessage] = useState("");

  const isReturnPeriodValid = (updatedAt, returnPeriod) => {
    const updatedDate = new Date(updatedAt);
    const today = new Date();
    const diffInDays = Math.floor(
      (today - updatedDate) / (1000 * 60 * 60 * 24)
    );

    return diffInDays <= Number(returnPeriod);
  };

  const handleReturnClick = () => {
    const returnPeriod = Number(appSetupdata?.return_period);
    const updatedAt = order?.updatedAt;

    const isValid = isReturnPeriodValid(updatedAt, returnPeriod);

    if (!isValid) {
      setErrorMessage(
        "Return period has expired. You can't return this order."
      );
    } else {
      setErrorMessage("");
      navigate.push(`/return-order/${encodeId(order?.id)}`);
    }
  };

  return (
    <>
      <section className="Receiver_info_holder">
        <div className="text_holder">
          <h4>{order?.User_Address?.first_name}</h4>
          <div className="name_holder">
            <div>
              <div className="icon_holder">
                <FontAwesomeIcon className="info_icon" icon={faPhone} />
              </div>
            </div>
            <p> +{order?.User_Address?.contact_no}</p>
          </div>

          <p>Apartment</p>
          <div className="name_holder">
            <div>
              <div className="icon_holder">
                <FontAwesomeIcon className="info_icon" icon={faLocationDot} />
              </div>
            </div>
            <p>
              {" "}
              {order?.User_Address?.building},{order?.User_Address?.street},
              {order?.User_Address?.Users_Address_Detail?.City?.name},{" "}
              {order?.User_Address?.Users_Address_Detail?.State?.name},–{" "}
              {order?.User_Address?.Users_Address_Detail?.Pincode?.name},{" "}
              {order?.User_Address?.Users_Address_Detail?.Country?.name}.
            </p>
          </div>

          {/* {order?.order_status_id !== 6 && (
            <p
              style={{
                color: "red",
                fontSize: "0.9rem",
                marginBottom: "8px",
              }}
            >
              You can cancel this order within {appSetupdata.cancel_period} hour
              from the order date as per our cancellation policy.
            </p>
          )} */}

          {appSetupdata?.cancel_period &&
            order?.order_status_id !== 6 &&
            (() => {
              const orderTime = new Date(order?.createdAt);
              const now = new Date();
              const diffInHours = (now - orderTime) / (1000 * 60 * 60);
              const canCancel =
                diffInHours < Number(appSetupdata.cancel_period);

              return (
                <>
                  <p
                    style={{
                      color: canCancel ? "red" : "gray",
                      fontSize: "0.9rem",
                      marginBottom: "8px",
                    }}
                  >
                    {canCancel &&
                      `You can cancel this order within ${appSetupdata.cancel_period} hour(s) from the order date as per our cancellation policy.`}
                  </p>
                  <Cancel_Order_btn
                    order={order}
                    btnText="Cancel Order"
                    disabled={!canCancel}
                    onClick={() => canCancel && handleClick(order?.id)} // prevent click action
                  />
                </>
              );
            })()}

          {/* {order?.order_status_id === 2 && (
            <Cancel_Order_btn order={order} btnText={"Cancel Order"} onClick={()=>handleClick(order?.id)} />
          )} */}
          {/* {order?.order_status_id === 6 && (
            <Cancel_Order_btn order={order} btnText={"Return Order"} onClick={()=>handleClickReturn(order?.id)} />
          )} */}
          {order?.order_status_id === 6 && (
            <div>
              <p
                style={{
                  color: "red",
                  fontSize: "0.9rem",
                  marginBottom: "8px",
                }}
              >
                {isReturnPeriodValid(
                  order?.updatedAt,
                  appSetupdata?.return_period
                ) &&
                  `You can return this order within ${appSetupdata.return_period}
                  days from the delivery date as per our return policy.`}
              </p>
              <Cancel_Order_btn
                order={order}
                disabled={
                  !isReturnPeriodValid(
                    order?.updatedAt,
                    appSetupdata?.return_period
                  )
                }
                btnText={"Return Order"}
                onClick={() =>
                  isReturnPeriodValid(
                    order?.updatedAt,
                    appSetupdata?.return_period
                  ) && handleReturnClick(order?.id)
                }
                // onClick={handleReturnClick}
              />
            </div>
          )}

          {errorMessage && (
            <p style={{ color: "red", marginTop: "8px" }}>{errorMessage}</p>
          )}
        </div>
      </section>
    </>
  );
}

export default Receiver_info_holder;
