/* 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 { placeInternationalOrder } from "../../../../Api/InternationalOrderApi";
import SelectOptions from "../../../TextField/SelectOptions";
import { getMasterList } from "../../../../Api/MastersApi";
import OrderPlacedModal from "./Step3/OrderPlacedModal";

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,
}) => {
  const router = useRouter();
  const createOrderData: any = useAppSelector((state) => state.createOrder);
  const step1Data = createOrderData?.step1;
  const step2Data = createOrderData?.step2;
  const step3Data = createOrderData?.step3;

  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" | "Night"
  >("Morning");
  const [customDate, setCustomDate] = useState<string>("");
  const [contactNumber, setContactNumber] = useState<string>(
    step3Data?.senderPhone || ""
  );
  const [pickupAddress, setPickupAddress] = useState<string>(
    step3Data?.senderAddress || ""
  );
  const [isEditingContact, setIsEditingContact] = useState<boolean>(false);
  const [isEditingAddress, setIsEditingAddress] = useState<boolean>(false);
  const [countries, setCountries] = useState<any[]>([]);
  const [goodsOrigin, setGoodsOrigin] = useState<any>(
    step1Data?.fromCountry || null
  );
  const [isEditingGoodsOrigin, setIsEditingGoodsOrigin] =
    useState<boolean>(false);

  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_time: pickupTime,
        pickup_contact_number: contactNumber,
        pickup_address: pickupAddress,
      };

      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);
    }
  };

  return (
    <>
      {isLoading && <HourGlassLoader />}
           <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">
                    {step1Data?.totalWeight} 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)}
                          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">
                    {step1Data?.totalWeight} 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}{" "}
                    {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)}
                      ></i>
                    </div>
                  )}
                </div>

                <div className="mb-4">
                  <label className="font-13 font-600 mb-2">
                    Pickup Address
                  </label>
                  {!isEditingAddress ? (
                    <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}
                        </span>
                      </div>
                      <i
                        className="ri-edit-box-line text-muted cursor-pointer font-16"
                        onClick={() => setIsEditingAddress(true)}
                      ></i>
                    </div>
                  ) : (
                    <div className="position-relative">
                      <div className="input-group">
                        <span className="input-group-text bg-light border-end-0">
                          <i className="ri-map-pin-fill text-muted"></i>
                        </span>
                        <input
                          type="text"
                          className="form-control bg-light border-start-0 ps-0"
                          value={pickupAddress}
                          onChange={(e) => setPickupAddress(e.target.value)}
                        />
                        <span
                          className="input-group-text bg-light border-start-0 cursor-pointer"
                          onClick={() => setIsEditingAddress(false)}
                        >
                          <i className="ri-check-line text-success font-18"></i>
                        </span>
                      </div>
                    </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={() => setPickupDate(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}
                      onChange={(e) => setCustomDate(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", "Night"].map((opt) => (
                      <button
                        key={opt}
                        className={`btn btn-sm rounded-pill px-3 py-2 ${
                          pickupTime === opt
                            ? "btn-purple"
                            : "btn-light text-muted"
                        }`}
                        onClick={() => setPickupTime(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 === "Night" && (
                          <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>{`
        .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];
};
