/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState } from "react";
import CreateOrderFooter from "./CreateOrderFooter";
import HourGlassLoader from "../../../Loader/Loader";
import { useAppSelector } from "@/Redux/Hooks";
import Swal from "sweetalert2";
import { useRouter } from "next/navigation";
import InternationalPhoneInput from "../../../TextField/InternationalPhoneInput";
import {
  getInternationalDraftOrderDetails,
  initiateInternationalDraftOrder,
  placeInternationalOrder,
} from "../../../../Api/InternationalOrderApi";
import SelectOptions from "../../../TextField/SelectOptions";
import { getMasterList } from "../../../../Api/MastersApi";
import OrderPlacedModal from "./Step3/OrderPlacedModal";
import AddressList from "../../MyProfile/Containers/AddressList";
import Modal from "../../../Modal/Modal";
import { showSuccess, showError } from "../../../utlits/toast";

type Step4Props = {
  step: number;
  setStep: React.Dispatch<React.SetStateAction<number>>;
  defaultOrderDetails: any;
  isEditMode?: boolean;
  onSave: (data: any) => void;
};

const Step4: React.FC<Step4Props> = ({
  step,
  setStep,
  defaultOrderDetails,
  isEditMode,
  onSave,
}) => {
  const router = useRouter();
  const createOrderData: any = useAppSelector((state) => state.createOrder);
  const step1Data = createOrderData?.step1;
  const step2Data = createOrderData?.step2;
  const step3Data = createOrderData?.step3;
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const step4Data = createOrderData?.step4;

  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [orderPlacedModalVisible, setOrderPlacedModalVisible] =
    useState<boolean>(false);
  const [placedOrderNumber, setPlacedOrderNumber] = useState<string | number>(
    "",
  );
  const [pickupDate, setPickupDate] = useState<"Today" | "Tomorrow" | "Custom">(
    "Today",
  );
  const [pickupTime, setPickupTime] = useState<
    "Morning" | "Afternoon" | "Evening"
  >("Morning");
  const [customDate, setCustomDate] = useState<string>("");
  const getMinCustomDate = () => {
    const date = new Date();
    date.setDate(date.getDate() + 2); // Day after tomorrow
    return date.toISOString().split("T")[0];
  };
  const [contactNumber, setContactNumber] = useState<string>(
    step3Data?.senderPhone || "",
  );
  const [pickupAddress, setPickupAddress] = useState<string>(
    step3Data?.senderAddress || "",
  );
  const [isEditingContact, setIsEditingContact] = useState<boolean>(false);
  const [countries, setCountries] = useState<any[]>([]);
  const [goodsOrigin, setGoodsOrigin] = useState<any>(
    step1Data?.fromCountry || null,
  );
  const [isEditingGoodsOrigin, setIsEditingGoodsOrigin] =
    useState<boolean>(false);
  const [showAddressList, setShowAddressList] = useState<boolean>(false);
  const [pickupAddressId, setPickupAddressId] = useState<number | null>(null);

  React.useEffect(() => {
    const fetchCountries = async () => {
      const res = await getMasterList("country");
      if (res?.status) {
        setCountries(
          res.data.map((c: any) => ({
            value: c.id,
            label: c.name,
            name: c.name,
            code: c.code,
          })),
        );
      }
    };

    fetchCountries();
  }, []);

  const handlePlaceOrder = async () => {
    setIsLoading(true);
    try {
      // Construct final payload
      const payload = {
        draft_order_id: step1Data.draft_order_id,
        goods_origin_country_id: goodsOrigin?.value,
        pickup_date:
          pickupDate === "Custom"
            ? customDate
            : getPickupDateString(pickupDate),
        pickup_slot_type:
          pickupTime === "Morning" ? 1 : pickupTime === "Afternoon" ? 2 : 3,
        pickup_contact_number: contactNumber,
        pickup_address: pickupAddress,
        pickup_address_id: pickupAddressId,
      };

      console.log("Placing Order with Payload:", payload);

      const response = await placeInternationalOrder(payload);

      if (response.status) {
        // Swal.fire({
        //   icon: "success",
        //   title: "Order Placed!",
        //   text: "Your international order has been successfully created.",
        //   confirmButtonText: "Go to Dashboard",
        // }).then(() => {
        // });
        const orderNo =
          response?.data?.order_no ||
          response?.data?.orderNumber ||
          response?.data?.id ||
          response?.data ||
          "";
        setPlacedOrderNumber(orderNo);
        setOrderPlacedModalVisible(true);
      } else {
        throw new Error(response.message || "Failed to place order");
      }
    } catch (error: any) {
      console.error("Order placement failed:", error);
      Swal.fire({
        icon: "error",
        title: "Oops...",
        text: error.message || "Something went wrong while placing your order.",
      });
    } finally {
      setIsLoading(false);
    }
  };

  const allData = JSON.parse(localStorage.getItem("ALL_DATA") || "{}");
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleAddressSelect = () => {
    const addresses = allData?.data?.addresses || [];
    const primaryAddress =
      addresses.find((addr: any) => addr.is_primary) || addresses[0] || null;

    const address = primaryAddress || null;

    const addressId = address?.id || null;
    setPickupAddressId(addressId);
    setPickupAddress(
      `${address?.addressLineOne || ""}${address?.addressLineTwo ? `, ${address.addressLineTwo}` : ""}, ${address?.building?.code || ""}${address?.building?.name ? ` - ${address.building.name}` : ""}, ${address?.road?.code || ""}${address?.road?.name ? ` - ${address.road.name}` : ""}, ${address?.block?.code || ""}${address?.block?.name ? ` - ${address.block.name}` : ""}`,
    );
    // Save pickup_address_id to Redux
    if (onSave) {
      onSave({
        pickup_address_id: addressId,
      });
    }
    setShowAddressList(false);
  };

  const toggleAddressList = async () => {
    setShowAddressList((prev) => !prev);

    try {
      const addresses = allData?.data?.addresses || [];
      const primaryAddress =
        addresses.find((addr: any) => addr.is_primary) || addresses[0] || null;

      const address = primaryAddress || null;

      const addressId = address?.id || null;
      setPickupAddress(
        `${address?.addressLineOne || ""}${address?.addressLineTwo ? `, ${address.addressLineTwo}` : ""}, ${address?.building?.code || ""}${address?.building?.name ? ` - ${address.building.name}` : ""}, ${address?.road?.code || ""}${address?.road?.name ? ` - ${address.road.name}` : ""}, ${address?.block?.code || ""}${address?.block?.name ? ` - ${address.block.name}` : ""}`,
      );
      // Save pickup_address_id to Redux
      if (onSave) {
        onSave({
          pickup_address_id: addressId,
        });
      }
      const step1 = JSON.parse(
        localStorage.getItem("CREATE_INTL_STEP1") || "{}",
      );

      const payload = {
        draft_order_id: step1.draft_order_id,
        pickup_address_id: addressId,
        package_details: step1.package_details?.map((pkg: any) => ({
          weight: Number(pkg.weight),
          length: Number(pkg.length),
          width: Number(pkg.width),
          height: Number(pkg.height),
          package_description: pkg.package_description || "",
          customer_input_package_value: Number(
            pkg.customer_input_package_value,
          ),
        })),
      };

      const response = await initiateInternationalDraftOrder(payload);
      if (response.status)
        // ✅ SUCCESS TOAST
        showSuccess("Pickup address updated successfully");
      else showError("Failed to update pickup address");
    } catch (error: any) {
      console.error(error);

      // ❌ ERROR TOAST (API + validation safe)
      showError(
        error?.response?.data?.message ||
          error?.message ||
          "Failed to update draft order",
      );
    }
  };

  const handlePickupContactUpdate = async (_phone_no: string) => {
    try {
      const step1 = JSON.parse(
        localStorage.getItem("CREATE_INTL_STEP1") || "{}",
      );

      const payload = {
        draft_order_id: step1.draft_order_id,
        pickup_mobile_number: _phone_no,
        package_details: step1.package_details?.map((pkg: any) => ({
          weight: Number(pkg.weight),
          length: Number(pkg.length),
          width: Number(pkg.width),
          height: Number(pkg.height),
          package_description: pkg.package_description || "",
          customer_input_package_value: Number(
            pkg.customer_input_package_value,
          ),
        })),
      };

      const response = await initiateInternationalDraftOrder(payload);
      if (response.status)
        // ✅ SUCCESS TOAST
        showSuccess("Pickup contact number updated successfully");
      else showError("Failed to update pickup contact number");
    } catch (error: any) {
      console.error(error);

      // ❌ ERROR TOAST (API + validation safe)
      showError(
        error?.response?.data?.message ||
          error?.message ||
          "Failed to update draft order",
      );
    }
  };

  const handleUpdatePickupTime = async (
    _time: "Morning" | "Afternoon" | "Evening",
  ) => {
    try {
      const step1Raw = localStorage.getItem("CREATE_INTL_STEP1");
      if (!step1Raw) {
        throw new Error("Draft order not found");
      }

      const step1 = JSON.parse(step1Raw);

      const payload = {
        draft_order_id: step1.draft_order_id,
        pickup_slot_type:
          _time === "Morning" ? 1 : _time === "Afternoon" ? 2 : 3,
        package_details: step1.package_details?.map((pkg: any) => ({
          weight: Number(pkg.weight),
          length: Number(pkg.length),
          width: Number(pkg.width),
          height: Number(pkg.height),
          package_description: pkg.package_description || "",
          customer_input_package_value: Number(
            pkg.customer_input_package_value,
          ),
        })),
      };

      const response = await initiateInternationalDraftOrder(payload);

      if (!response?.status) {
        throw new Error("Failed to update pickup time");
      }

      setPickupTime(_time);
      showSuccess("Pickup time updated successfully");
    } catch (error: any) {
      console.error(error);
      showError(
        error?.response?.data?.message ||
          error?.message ||
          "Failed to update pickup time",
      );
    }
  };

  const handleGoodOriginUpdate = async (_country_id: number) => {
    try {
      const step1 = JSON.parse(
        localStorage.getItem("CREATE_INTL_STEP1") || "{}",
      );

      const payload = {
        draft_order_id: step1.draft_order_id,
        goods_origin_country_id: _country_id,
        package_details: step1.package_details?.map((pkg: any) => ({
          weight: Number(pkg.weight),
          length: Number(pkg.length),
          width: Number(pkg.width),
          height: Number(pkg.height),
          package_description: pkg.package_description || "",
          customer_input_package_value: Number(
            pkg.customer_input_package_value,
          ),
        })),
      };

      const response = await initiateInternationalDraftOrder(payload);
      if (response.status)
        // ✅ SUCCESS TOAST
        showSuccess("Goods origin updated successfully");
      else showError("Failed to update goods origin");
    } catch (error: any) {
      console.error(error);

      // ❌ ERROR TOAST (API + validation safe)
      showError(
        error?.response?.data?.message ||
          error?.message ||
          "Failed to update draft order",
      );
    }
  };
  const resolvePickupDate = (
    type: "Today" | "Tomorrow" | "Custom",
    _customDate?: string,
  ) => {
    const today = new Date();

    if (type === "Today") {
      return today.toISOString().slice(0, 10);
    }

    if (type === "Tomorrow") {
      today.setDate(today.getDate() + 1);
      return today.toISOString().slice(0, 10);
    }

    if (type === "Custom") {
      const dateToUse = _customDate || customDate;
      if (!dateToUse) {
        throw new Error("Please select a pickup date");
      }
      return dateToUse;
    }

    throw new Error("Invalid pickup date");
  };

  const handleUpdatePickupDate = async (
    _date: "Today" | "Tomorrow" | "Custom",
    _customDate?: string,
  ) => {
    try {
      const step1Raw = localStorage.getItem("CREATE_INTL_STEP1");
      if (!step1Raw) {
        throw new Error("Draft order not found");
      }

      const step1 = JSON.parse(step1Raw);

      // 🔐 Resolve actual pickup date
      const pickup_date = resolvePickupDate(_date, _customDate);

      const payload = {
        draft_order_id: step1.draft_order_id,
        pickup_date,
        package_details: step1.package_details?.map((pkg: any) => ({
          weight: Number(pkg.weight),
          length: Number(pkg.length),
          width: Number(pkg.width),
          height: Number(pkg.height),
          package_description: pkg.package_description || "",
          customer_input_package_value: Number(
            pkg.customer_input_package_value,
          ),
        })),
      };

      const response = await initiateInternationalDraftOrder(payload);

      if (!response?.status) {
        throw new Error("Failed to update pickup date");
      }

      // ✅ Update state ONLY after success
      setPickupDate(_date);

      showSuccess("Pickup date updated successfully");
    } catch (error: any) {
      console.error(error);

      showError(
        error?.response?.data?.message ||
          error?.message ||
          "Failed to update pickup date",
      );
    }
  };

  const [step4Detail, setStep4Data] = useState<any>(null);
  React.useEffect(() => {
    const loadDraftDetails = async () => {
      try {
        const draftOrderId = step1Data?.draft_order_id;
        if (!draftOrderId) return;

        const res = await getInternationalDraftOrderDetails(draftOrderId);

        if (res?.status) {
          const data = res.data;

          setStep4Data(data);

          // ✅ Optional: save to localStorage (refresh-safe)
          localStorage.setItem("CREATE_INTL_STEP4", JSON.stringify(data));

          // ✅ Hydrate local states
        }
      } catch (err) {
        console.error("Failed to load step4 data", err);
      }
    };

    loadDraftDetails();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const stepPreview = JSON.parse(
    localStorage.getItem("CREATE_INTL_STEP4") || "{}",
  );
  return (
    <>
      {isLoading && <HourGlassLoader />}
      <Modal
        show={showAddressList}
        onHide={toggleAddressList}
        header={false}
        title=""
        fullscreen={"md"}
        centered={true}
        classname=""
        // custom-center-modal address-select-modal
        position={"center"}
      >
        <AddressList
          modal={true}
          toggleAddressChange={toggleAddressList}
          // onSelect={handleAddressSelect}
          // selectedAddressId={pickupAddressId}
        />
      </Modal>
      <OrderPlacedModal
        visible={orderPlacedModalVisible}
        orderNumber={placedOrderNumber}
        onMyOrders={() => {
          setOrderPlacedModalVisible(false);
          router.push("/dashboard/orders");
        }}
        onHome={() => {
          setOrderPlacedModalVisible(false);
          router.push("/dashboard");
        }}
        onClose={() => setOrderPlacedModalVisible(false)}
      />
      <div className="scrollWrap step4-international p-4">
        <div className="receipt-container shadow-sm">
          <div className="receipt-perforation"></div>
          <div className="receipt-content bg-white p-5">
            <div className="row g-5">
              {/* Left Column: Order Summary */}
              <div className="col-lg-6 border-end-lg">
                {/* From & To */}
                <div className="row mb-4">
                  <div className="col-md-6">
                    <h6 className="text-muted font-12 mb-3">From</h6>
                    <div className="d-flex align-items-start mb-2">
                      <i className="ri-user-fill text-muted me-2 mt-1 font-14"></i>
                      <div className="font-14 font-700">
                        {step3Data?.senderName}
                      </div>
                    </div>
                    <div className="d-flex align-items-start mb-2">
                      <i className="ri-phone-fill text-muted me-2 mt-1 font-14"></i>
                      <div className="font-12 text-muted">
                        {step3Data?.senderPhone}
                      </div>
                    </div>
                    <div className="d-flex align-items-start mb-2">
                      <i className="ri-mail-fill text-muted me-2 mt-1 font-14"></i>
                      <div className="font-12 text-muted">
                        {step3Data?.senderEmail}
                      </div>
                    </div>
                    <div className="d-flex align-items-start">
                      <i className="ri-map-pin-fill text-muted me-2 mt-1 font-14"></i>
                      <div className="font-12 text-muted">
                        {step3Data?.senderAddress}
                        {step3Data?.senderAddress2 &&
                          `, ${step3Data.senderAddress2}`}
                        <br />
                        {step3Data?.senderCity?.label}, {step3Data?.senderState}{" "}
                        {step3Data?.senderPostalCode}
                        <br />
                        {step3Data?.senderCountry?.label}
                      </div>
                    </div>
                  </div>
                  <div className="col-md-6">
                    <h6 className="text-muted font-12 mb-3">To</h6>
                    <div className="d-flex align-items-start mb-2">
                      <i className="ri-user-fill text-muted me-2 mt-1 font-14"></i>
                      <div className="font-14 font-700">
                        {step3Data?.receiverName}
                      </div>
                    </div>
                    <div className="d-flex align-items-start mb-2">
                      <i className="ri-phone-fill text-muted me-2 mt-1 font-14"></i>
                      <div className="font-12 text-muted">
                        {step3Data?.receiverPhone}
                      </div>
                    </div>
                    <div className="d-flex align-items-start mb-2">
                      <i className="ri-mail-fill text-muted me-2 mt-1 font-14"></i>
                      <div className="font-12 text-muted">
                        {step3Data?.receiverEmail}
                      </div>
                    </div>
                    <div className="d-flex align-items-start">
                      <i className="ri-map-pin-fill text-muted me-2 mt-1 font-14"></i>
                      <div className="font-12 text-muted">
                        {step3Data?.receiverAddress}
                        {step3Data?.receiverAddress2 &&
                          `, ${step3Data.receiverAddress2}`}
                        <br />
                        {step3Data?.receiverCity?.label},{" "}
                        {step3Data?.receiverState}{" "}
                        {step3Data?.receiverPostalCode}
                        <br />
                        {step3Data?.receiverCountry?.label}
                      </div>
                    </div>
                  </div>
                </div>

                <hr className="text-muted opacity-25 my-4" />

                {/* Details List */}
                <div className="d-flex justify-content-between py-3 border-bottom">
                  <span className="text-muted font-13">
                    Tax ID/VAT/EIN Number
                  </span>
                  <span className="font-13 font-700">
                    {step3Data?.senderTaxId || "TXN000001"}
                  </span>
                </div>
                <div className="d-flex justify-content-between py-3 border-bottom">
                  <span className="text-muted font-13">Package Type</span>
                  <span className="font-13 font-700">
                    {step1Data?.shipmentContent}
                  </span>
                </div>
                <div className="d-flex justify-content-between py-3 border-bottom">
                  <span className="text-muted font-13">Number of Packages</span>
                  <span className="font-13 font-700">
                    {step1Data?.noOfPackages}
                  </span>
                </div>
                <div className="d-flex justify-content-between py-3 border-bottom">
                  <span className="text-muted font-13">Weight</span>
                  <span className="font-13 font-700">
                    {stepPreview?.totalWeight ?? 0} KG
                  </span>
                </div>
                <div className="d-flex justify-content-between py-3 border-bottom">
                  <span className="text-muted font-13">Goods Origin</span>

                  {!isEditingGoodsOrigin ? (
                    <div className="d-flex align-items-center gap-2">
                      <span className="font-13 font-700">
                        {goodsOrigin?.name || "--"}
                      </span>
                      <i
                        className="ri-edit-box-line text-muted cursor-pointer font-16"
                        onClick={() => {
                          setIsEditingGoodsOrigin(true);
                        }}
                      ></i>
                    </div>
                  ) : (
                    <div
                      className="d-flex align-items-center gap-2"
                      style={{ minWidth: 220 }}
                    >
                      <SelectOptions
                        name="goodsOrigin"
                        optionsData={countries}
                        value={goodsOrigin}
                        onChange={(val: any) => {
                          setGoodsOrigin(val);
                          handleGoodOriginUpdate(val?.id);
                        }}
                        placeholder="Select Country"
                      />
                      <i
                        className="ri-check-line text-success cursor-pointer font-18"
                        onClick={() => setIsEditingGoodsOrigin(false)}
                      ></i>
                    </div>
                  )}
                </div>
                <div className="d-flex justify-content-between py-3 border-bottom">
                  <span className="text-muted font-13">Country</span>
                  <span className="font-13 font-700">
                    {step1Data?.toCountry?.name}
                  </span>
                </div>
                <div className="d-flex justify-content-between py-3 border-bottom">
                  <span className="text-muted font-13">City</span>
                  <span className="font-13 font-700">
                    {step1Data?.toCity?.name || "--"}
                  </span>
                </div>
                {/* <div className="d-flex justify-content-between py-3">
                  <span className="text-muted font-13">Remarks</span>
                  <span className="font-13 font-700">
                    {step2Data?.remarks || "--"}
                  </span>
                </div> */}
              </div>

              {/* Right Column: Schedule Pickup */}
              <div className="col-lg-6">
                <h5 className="font-16 font-700 mb-4 text-center">
                  Schedule Pickup
                </h5>

                <div className="d-flex justify-content-between py-2">
                  <span className="text-muted font-13">No. of Packages</span>
                  <span className="font-13 font-700">
                    {String(step1Data?.noOfPackages).padStart(2, "0")}
                  </span>
                </div>
                <div className="d-flex justify-content-between py-2 mb-3">
                  <span className="text-muted font-13">Total Weight</span>
                  <span className="font-13 font-700">
                    {stepPreview?.totalWeight ?? 0} Kg
                  </span>
                </div>

                <div className="d-flex justify-content-between align-items-center mb-4">
                  <h5 className="font-18 font-700 mb-0">Shipping Charge</h5>
                  <h5 className="font-18 font-700 text-danger mb-0">
                    {step2Data?.selectedServiceDetails?.currency}{" "}
                    {step4Detail?.calculatedTotalShippingCharge?.toFixed(3) ??
                      step2Data?.selectedServiceDetails?.price?.toFixed(3)}
                  </h5>
                </div>

                <div className="mb-3">
                  <label className="font-13 font-600 mb-2">
                    Contact Number
                  </label>
                  {!isEditingContact ? (
                    <div className="d-flex align-items-center justify-content-between">
                      <div className="d-flex align-items-center">
                        <i className="ri-phone-fill text-muted me-2 font-16"></i>
                        <span className="font-13 font-600 text-dark">
                          {contactNumber}
                        </span>
                      </div>
                      <i
                        className="ri-edit-box-line text-muted cursor-pointer font-16"
                        onClick={() => setIsEditingContact(true)}
                      ></i>
                    </div>
                  ) : (
                    <div className="position-relative">
                      <InternationalPhoneInput
                        value={contactNumber}
                        onChange={(val) => {
                          setContactNumber(val);
                        }}
                        placeholder="Contact Number"
                        className="bg-light"
                      />
                      <i
                        className="ri-check-line position-absolute end-0 top-50 translate-middle-y me-3 text-success cursor-pointer font-18"
                        style={{ zIndex: 10 }}
                        onClick={() => {
                          setIsEditingContact(false);
                          handlePickupContactUpdate(contactNumber);
                        }}
                      ></i>
                    </div>
                  )}
                </div>

                <div className="mb-4">
                  <label className="font-13 font-600 mb-2">
                    Pickup Address
                  </label>
                  <div className="d-flex align-items-start justify-content-between">
                    <div className="d-flex align-items-start">
                      <i className="ri-map-pin-fill text-muted me-2 mt-1 font-16"></i>
                      <span className="font-13 font-600 text-dark">
                        {pickupAddress || "Select pickup address"}
                      </span>
                    </div>
                    <i
                      className="ri-edit-box-line text-muted cursor-pointer font-16"
                      onClick={() => setShowAddressList(true)}
                    ></i>
                  </div>
                </div>

                <div className="mb-4">
                  <label className="font-13 font-600 mb-2">
                    Choose Pickup Date
                  </label>
                  <div className="d-flex gap-2">
                    {["Today", "Tomorrow", "Custom"].map((opt) => (
                      <button
                        key={opt}
                        className={`btn btn-sm rounded-pill px-3 py-2 ${
                          pickupDate === opt
                            ? "btn-purple"
                            : "btn-light text-muted"
                        }`}
                        onClick={() => {
                          if (opt === "Custom") {
                            setPickupDate("Custom");
                          } else {
                            handleUpdatePickupDate(opt as any);
                          }
                        }}
                      >
                        {opt === "Today" && (
                          <i className="ri-time-line me-1"></i>
                        )}
                        {opt === "Tomorrow" && (
                          <i className="ri-checkbox-circle-fill me-1"></i>
                        )}
                        {opt === "Custom" && (
                          <i className="ri-calendar-line me-1"></i>
                        )}
                        {opt}
                      </button>
                    ))}
                  </div>
                  {pickupDate === "Custom" && (
                    <input
                      type="date"
                      className="form-control mt-2"
                      value={customDate}
                      min={getMinCustomDate()}
                      onChange={(e) => {
                        setCustomDate(e.target.value);
                        handleUpdatePickupDate("Custom", e.target.value);
                      }}
                    />
                  )}
                </div>

                <div className="mb-4">
                  <label className="font-13 font-600 mb-2">
                    Choose Pickup Time
                  </label>
                  <div className="d-flex gap-2">
                    {["Morning", "Afternoon", "Evening"].map((opt) => (
                      <button
                        key={opt}
                        className={`btn btn-sm rounded-pill px-3 py-2 ${
                          pickupTime === opt
                            ? "btn-purple"
                            : "btn-light text-muted"
                        }`}
                        onClick={() => handleUpdatePickupTime(opt as any)}
                      >
                        {opt === "Morning" && (
                          <i className="ri-sun-line me-1"></i>
                        )}
                        {opt === "Afternoon" && (
                          <i className="ri-checkbox-circle-fill me-1"></i>
                        )}
                        {opt === "Evening" && (
                          <i className="ri-moon-line me-1"></i>
                        )}
                        {opt}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <CreateOrderFooter
        step={step}
        setStep={async (nextStep) => {
          if (nextStep === 5) {
            await handlePlaceOrder();
          } else {
            setStep(nextStep);
          }
        }}
        validation={() => true}
        backButton={true}
        backButtonFn={() => setStep(3)}
        defaultOrderDetails={defaultOrderDetails}
        isEditMode={isEditMode}
        // validation={() => !isEditingGoodsOrigin}
        // nextButtonText="PLACE ORDER"
      />

      <style jsx>{`
        :global(.address-select-modal .modal-dialog) {
          max-width: 1100px;
          margin: 1.75rem auto;
        }
        :global(.address-select-modal .modal-content) {
          border-radius: 16px;
          padding: 0;
          width: 100%;
        }
        :global(.address-select-modal .modal-body) {
          padding: 20px;
        }
        :global(.address-select-modal .title-address) {
          padding: 0 10px;
        }
        :global(.address-select-modal .add-address-row) {
          max-height: 55vh;
          overflow-y: auto;
          padding: 0 10px;
        }
        :global(.address-select-modal .col-lg-6.order-list-box) {
          margin-bottom: 0.5rem;
        }
        @media (max-width: 767px) {
          :global(.address-select-modal .modal-content) {
            max-width: 95%;
            margin: 20px auto;
          }
          :global(.address-select-modal .add-address-row) {
            max-height: 65vh;
          }
        }
        .receipt-container {
          border-radius: 0 0 12px 12px;
          overflow: hidden;
        }
        .receipt-perforation {
          height: 20px;
          background-image: radial-gradient(
            circle at 10px 0,
            transparent 10px,
            white 10px
          );
          background-size: 20px 20px;
          background-position: 0 0;
          background-repeat: repeat-x;
          filter: drop-shadow(0 4px 2px rgba(0, 0, 0, 0.05));
          margin-bottom: -1px; /* Overlap slightly to avoid gaps */
        }
        .receipt-content {
          border-radius: 0 0 12px 12px;
        }
        .font-12 {
          font-size: 12px;
        }
        .font-13 {
          font-size: 13px;
        }
        .font-14 {
          font-size: 14px;
        }
        .font-16 {
          font-size: 16px;
        }
        .font-18 {
          font-size: 18px;
        }
        .font-600 {
          font-weight: 600;
        }
        .font-700 {
          font-weight: 700;
        }
        .text-dark-blue {
          color: #000080 !important;
        }
        .btn-purple {
          background-color: #7b3f9b;
          color: white;
          border: none;
        }
        .btn-light {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
        }
        .border-end-lg {
          border-right: 1px dashed #dee2e6;
        }
        .cursor-pointer {
          cursor: pointer;
        }
        @media (max-width: 991px) {
          .border-end-lg {
            border-right: none;
            border-bottom: 1px dashed #dee2e6;
            padding-bottom: 1.5rem;
            margin-bottom: 1.5rem;
          }
        }
      `}</style>
    </>
  );
};

export default Step4;

const getPickupDateString = (type: "Today" | "Tomorrow") => {
  const date = new Date();
  if (type === "Tomorrow") {
    date.setDate(date.getDate() + 1);
  }
  return date.toISOString().split("T")[0];
};
