/* eslint-disable @typescript-eslint/no-explicit-any */
import { useAppSelector } from "@/Redux/Hooks";
import React, { useMemo } from "react";
import PlaceOrderForm from "./PlaceOrder/PlaceOrderForm";
import Link from "next/link";
import AddressList from "../pages/MyProfile/Containers/AddressList";
import PhoneEdit from "./PlaceOrder/PhoneEdit";
import {
  amountFormatWithCurrency,
  getFormattedAddress,
} from "../../lib/Helper";
import { OrderFlowType, UserTypes } from "@/Constant/enums";
import Swal from "sweetalert2";
interface PlaceOrderModalProps {
  onClose: () => void;
  handleMakePayment: () => void;
  openPaymentConfirmModal: boolean;
  togglePaymentConfirm: () => void;
}
const PlaceOrderModal: React.FC<PlaceOrderModalProps> = ({
  onClose,
  handleMakePayment,
}) => {
  const [addressChangeModal, setAddressChangeModal] =
    React.useState<boolean>(false);
  const toggleAddressChange = () => setAddressChangeModal(!addressChangeModal);
  const [MobileChangeModal, setMobileChangeModal] =
    React.useState<boolean>(false);
  const toggleMobileChange = () => setMobileChangeModal(!MobileChangeModal);
  const completeDetails: any = useAppSelector((state) => state.createOrder);
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  // ✅ compute validity
  const isFormValid = useMemo(() => {
    const date = completeDetails?.step3?.makePayment?.date;
    const time = completeDetails?.step3?.makePayment?.time;
    return Boolean(date && time);
  }, [completeDetails]);

  // ✅ final handler with safeguard
  const onConfirmClick = () => {
    if (!isFormValid) {
      Swal.fire({
        icon: "warning",
        title: "Oops...",
        text: !completeDetails?.step3?.makePayment?.date
          ? "Please select date"
          : "Please select time",
        confirmButtonText: "OK",
      });
      return;
    }
    handleMakePayment();
  };
  return (
    <>
      {addressChangeModal ? (
        <AddressList toggleAddressChange={toggleAddressChange} isReturn={completeDetails?.step3?.draftList?.[0]?.orderFlowType?.id === OrderFlowType.Return ? true : false} />
      ) : MobileChangeModal ? (
        <PhoneEdit allData={allData} toggleMobileChange={toggleMobileChange} isReturn={completeDetails?.step3?.draftList?.[0]?.orderFlowType?.id === OrderFlowType.Return ? true : false} />
      ) : (
        <div
          id="place-pickup-modal"
          className="pickup-scheduled-popup"
        // className="menu menu-box-modal pickup-scheduled-popup rounded-m bg-theme"
        // data-menu-width={375}
        // data-menu-height={520}
        >
          <div className="menu-title">
            <h1 className="font-22 font-800 pt-3">Schedule Pickup</h1>
            <a href="#" onClick={onClose} className="close-menu">
              <i className="fa fa-times" />
            </a>
          </div>
          <div className="content mt-2 mb-0">
            <div className="divider mt-n1 mb-2" />
            <div className="addressRow mb-2">
              {/* <div className="d-flex justify-content-between align-items-center">
                <h1 className="vcard-title font-15 font-700 text-capitalize mb-0 pb-0">
                  No.<span className="text-lowercase">of</span> Orders (
                  {completeDetails?.step3?.draftList?.length || 0})
                </h1>
                <p className="font-600 mb-n1 color-red2"><a href="#">Change</a></p>
              </div> */}
              {completeDetails?.step3?.draftList?.[0]?.orderFlowType?.id === OrderFlowType.Return ? (
                <div className="d-flex mb-0">
                  <div>
                    <h6 className="opacity-90 font-14 font-300">Order Type</h6>
                  </div>
                  <div className="ms-auto">
                    <h5 className="font-15 font-500">
                      <span className="badge bg-purple rounded-xl font-12 px-2">
                        {completeDetails?.step3?.draftList?.[0]?.orderFlowType?.id === OrderFlowType.Return ? 'Return ' : 'Forward '}
                      </span>
                    </h5>
                  </div>
                </div>
              ) : ''}
              <div className="d-flex mb-0">
                <div>
                  <h6 className="opacity-90 font-14 font-300">Service Type</h6>
                </div>
                <div className="ms-auto">
                  <h5 className="font-15 font-500">
                    <span className="badge card-status rounded-xl font-12 px-2">
                      {completeDetails?.step3?.draftList?.[0]?.service_type_details?.name}
                    </span>
                  </h5>
                </div>
              </div>
              <div className="d-flex mb-0">
                <div>
                  <h6 className="opacity-90 font-14 font-300">No.of Orders</h6>
                </div>
                <div className="ms-auto">
                  <h5 className="font-15 font-500">
                    {completeDetails?.step3?.orderPreview
                      ?.numberOfDraftOrders || 0}
                  </h5>
                </div>
              </div>
              <div className="d-flex mb-0">
                <div>
                  <h6 className="opacity-90 font-14 font-300">
                    No.of Packages
                  </h6>
                </div>
                <div className="ms-auto">
                  <h5 className="font-15 font-500">
                    {completeDetails?.step3?.orderPreview?.numberOfPackages ||
                      0}
                    {/* <span className="opacity-50 font-14">(500kg)</span> */}
                  </h5>
                </div>
              </div>
              {allData?.userType?.id === UserTypes.CorporateCodCustomer ? (
                <div className="d-flex mb-0">
                  <div>
                    <h6 className="opacity-90 font-14 font-300">COD Amount</h6>
                  </div>
                  <div className="ms-auto">
                    <h5 className="font-15 font-500 color-green-dark">
                      {" "}
                      {amountFormatWithCurrency(
                        completeDetails?.step3?.orderPreview?.totalCodAmount ||
                        0
                      )}{" "}
                    </h5>
                  </div>
                </div>
              ) : (
                ""
              )}
              {/* <div className="d-flex mb-0">
                <div>
                  <h6 className="opacity-90 font-14 font-300">Shipping Charge</h6>
                </div>
                <div className="ms-auto">
                  <h5 className="font-15 font-500 color-green-dark">
                    {" "}
                    {amountFormatWithCurrency(
                      completeDetails?.step3?.orderPreview
                        ?.calculatedTotalShippingCharge || 0
                    )}{" "}
                  </h5>
                </div>
              </div> */}
              {/* <div className="d-flex mb-1">
                <div>
                  <h6 className="opacity-90 font-14 font-300">Discount</h6>
                </div>
                <div className="ms-auto">
                  <h5 className="font-15 font-500 color-red-dark">BHD 99.00</h5>
                </div>
              </div> */}
              <div className="d-flex mb-0">
                <div>
                  <h3 className="font-700">Shipping Charge</h3>
                </div>
                <div className="ms-auto">
                  <h3 className="text-danger">
                    {" "}
                    {amountFormatWithCurrency(
                      completeDetails?.step3?.orderPreview
                        ?.calculatedTotalShippingCharge || 0
                    )}
                  </h3>
                </div>
              </div>

              <div className="vcard-field line-height-l pb-2 pt-0">
                <div className="d-float-center justify-content-between">
                  <h5
                    className="font-14 font-400 pb-1 mb-0 mt-0"
                    style={{ paddingTop: "8px", opacity: "0.6" }}
                  >
                    {completeDetails?.step3?.draftList?.[0]?.orderFlowType?.id === OrderFlowType.Return ? 'Delivery ' : 'Pickup '}Address
                  </h5>
                  <Link
                    href="#"
                    onClick={toggleAddressChange}
                    className="mb-0 mt-0 pb-1"
                    style={{ paddingTop: "8px" }}
                  >
                    <i className="fa fa-edit position-unset" />
                  </Link>
                </div>
                <div className="d-float-center justify-content-between">
                  <span className="font-600">
                    {/* <i className="fa fa-map-marker position-unset mt-n2" /> */}
                    <i className="ri-map-pin-line position-unset mt-n2" />
                    {/* <Image
                      className="order-icons img-fluid me-1"
                      src="/images/icons/location.svg"
                      alt="Box Icon"
                      width={18}
                      height={18}
                    /> */}{" "}
                    {/* Flat-1545, Building-78745 Road-4578, Block-987 */}
                    {getFormattedAddress()}
                  </span>
                </div>
                {completeDetails?.step3?.orderPreview?.senderAddressDetails ? (
                  <>
                    <h5
                      className="font-14 font-400 pb-1 mb-0 mt-0"
                      style={{ paddingTop: "8px", opacity: "0.6" }}
                    >
                      Sender Address
                    </h5>
                    <div className="d-float-center justify-content-between">
                      <span
                        className="font-600 ellipsis-tooltip"
                        title={
                          completeDetails?.step3?.orderPreview
                            ?.senderAddressDetails || ""
                        }
                      >
                        <i className="ri-map-pin-line position-unset mt-n2" />{" "}
                        {
                          completeDetails?.step3?.orderPreview
                            ?.senderAddressDetails
                        }
                      </span>
                    </div>
                  </>
                ) : (
                  ""
                )}
                {/* <PhoneEdit allData={allData} /> */}
                <h5
                  className="font-14 font-400 pb-1 mb-0 mt-0"
                  style={{ paddingTop: "8px", opacity: "0.6" }}
                >
                  {completeDetails?.step3?.draftList?.[0]?.orderFlowType?.id === OrderFlowType.Return ? 'Delivery ' : 'Pickup '} Contact Number
                </h5>
                <div className="d-float-center justify-content-between">
                  <span className="font-600">
                    {/* <i className="fa fa-phone position-unset mt-n2" /> */}
                    <i className="ri-phone-line position-unset mt-n2" />{" "}
                    {allData?.phone}
                  </span>
                  <Link href="#" onClick={toggleMobileChange} className="my-0">
                    <i className="fa fa-edit position-unset" />
                  </Link>
                </div>
              </div>
            </div>
            <PlaceOrderForm serviceType={completeDetails?.step3?.draftList?.[0]?.service_type_details} />
            {/* completeDetails?.step1?.serviceType */}
          </div>
          {/* ✅ inline error message */}
          {!isFormValid && (
            <div className="text-danger px-2 error-box select-error mb-3">
              {`Please select both date and time to continue`}
            </div>
          )}
          <div className="col-lg-12 px-lg-2">
            <button
              type="button"
              onClick={onConfirmClick}
              disabled={!isFormValid}
              className="btn btn-full w-100 btn-l font-600 font-13 bg-blue-dark mt-0 mb-2 rounded-s text-uppercase"
            >
              {!isFormValid ? 'Confirm Order' : 'Confirm Order'}
            </button>
          </div>
          {/* <a
            href="#"
            onClick={handleMakePayment}
            data-menu="menu-confirmation"
            className="btn btn-full delybell-primary font-13 btn-m font-600 m-3 rounded-s text-uppercase"
          >
            Confirm Order
          </a> */}
        </div>
      )}
    </>
  );
};

export default PlaceOrderModal;
