/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useState } from "react";
import CreateOrderFooter from "./CreateOrderFooter";
import SelectOptions, { OptionType } from "../../../TextField/SelectOptions";
import InternationalPhoneInput from "../../../TextField/InternationalPhoneInput";
import { useAppSelector } from "@/Redux/Hooks";
import {
  getMasterList,
  getInternationalCities,
} from "../../../../Api/MastersApi";
import { initiateInternationalDraftOrder } from "../../../../Api/InternationalOrderApi";
import { buildAddressText, resolveCountryCode } from "../../../../lib/Helper";
import RequiredStar from "./RequiredStar";
import AddressList from "../../MyProfile/Containers/AddressList";
import Modal from "../../../Modal/Modal";
import HourGlassLoader from "../../../Loader/Loader";
import Swal from "sweetalert2";

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

const Step3: React.FC<Step3Props> = ({
  onSave,
  step,
  setStep,
  defaultOrderDetails,
  isEditMode,
}) => {
  const createOrderData: any = useAppSelector((state) => state.createOrder);
  const step1Data = createOrderData?.step1;
  const step3Data = createOrderData?.step3;
  const step4Data = createOrderData?.step4;
  type Step3Errors = {
    senderCompanyName?: boolean;
    senderName?: boolean;
    senderPhone?: boolean;
    senderAddress?: boolean;
    senderCountry?: boolean;
    senderCity?: boolean;
    senderTaxId?: boolean;
    senderPostalCode?: boolean;
    senderAltPhone?: boolean;
    senderEmail?: boolean;
    senderAddress2?: boolean;
    senderSave?: boolean;

    receiverCompanyName?: boolean;
    receiverName?: boolean;
    receiverPhone?: boolean;
    receiverAddress?: boolean;
    receiverCountry?: boolean;
    receiverCity?: boolean;
    receiverTaxId?: boolean;
    receiverPostalCode?: boolean;
    receiverAltPhone?: boolean;
    receiverEmail?: boolean;
    receiverAddress2?: boolean;
    receiverSave?: boolean;
  };

  const [errors, setErrors] = useState<Step3Errors>({});
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // --- Sender State ---
  const [senderCompanyName, setSenderCompanyName] = useState<string>(
    step3Data?.senderCompanyName || "",
  );
  console.log(step3Data?.senderName, 'step3Data?.senderNamestep3Data?.senderNamestep3Data?.senderName')
  const [senderName, setSenderName] = useState<string>(
    step3Data?.senderName || "",
  );
  const [senderTaxId, setSenderTaxId] = useState<string>(
    step3Data?.senderTaxId || "",
  );
  const [senderCountry, setSenderCountry] = useState<OptionType | null>(
    step3Data?.senderCountry || step1Data?.fromCountry || null,
  );
  const [senderCity, setSenderCity] = useState<OptionType | null>(
    step3Data?.senderCity || step1Data?.fromCity || null,
  );
  const [senderPostalCode, setSenderPostalCode] = useState<string>(
    step3Data?.senderPostalCode || "",
  );
  const [senderPhone, setSenderPhone] = useState<string>(
    step3Data?.senderPhone || "",
  );
  const [senderAltPhone, setSenderAltPhone] = useState<string>(
    step3Data?.senderAltPhone || "",
  );
  const [senderEmail, setSenderEmail] = useState<string>(
    step3Data?.senderEmail || "",
  );
  const [senderAddress, setSenderAddress] = useState<string>(
    step3Data?.senderAddress || "",
  );
  const [senderAddress2, setSenderAddress2] = useState<string>(
    step3Data?.senderAddress2 || "",
  );
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [saveSender, setSaveSender] = useState<boolean>(
    step3Data?.saveSender ?? false,
  );

  // --- Receiver State ---
  const [receiverCompanyName, setReceiverCompanyName] = useState<string>(
    step3Data?.receiverCompanyName || "",
  );
  const [receiverName, setReceiverName] = useState<string>(
    step3Data?.receiverName || "",
  );
  const [receiverTaxId, setReceiverTaxId] = useState<string>(
    step3Data?.receiverTaxId || "",
  );
  const [receiverCountry, setReceiverCountry] = useState<OptionType | null>(
    step3Data?.receiverCountry || step1Data?.toCountry || null,
  );
  const [receiverCity, setReceiverCity] = useState<OptionType | null>(
    step3Data?.receiverCity || step1Data?.toCity || null,
  );
  const [receiverPostalCode, setReceiverPostalCode] = useState<string>(
    step3Data?.receiverPostalCode || "",
  );
  const [receiverPhone, setReceiverPhone] = useState<string>(
    step3Data?.receiverPhone || "",
  );
  const [receiverAltPhone, setReceiverAltPhone] = useState<string>(
    step3Data?.receiverAltPhone || "",
  );
  const [receiverEmail, setReceiverEmail] = useState<string>(
    step3Data?.receiverEmail || "",
  );
  const [receiverAddress, setReceiverAddress] = useState<string>(
    step3Data?.receiverAddress || "",
  );
  const [receiverAddress2, setReceiverAddress2] = useState<string>(
    step3Data?.receiverAddress2 || "",
  );
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [saveReceiver, setSaveReceiver] = useState<boolean>(
    step3Data?.saveReceiver ?? false,
  );

  // --- Lists ---
  const [countries, setCountries] = useState<OptionType[]>([]);
  const [senderCities, setSenderCities] = useState<OptionType[]>([]);
  const [receiverCities, setReceiverCities] = useState<OptionType[]>([]);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [pickupAddressId, setPickupAddressId] = useState<number | null>(() => {
    const saved = localStorage.getItem("PICKUP_ADDRESS_ID");
    return saved ? Number(saved) : step4Data?.pickup_address_id || null;
  });
  const [showAddressList, setShowAddressList] = useState<boolean>(false);
  const allData = JSON.parse(localStorage.getItem("ALL_DATA") || "{}");
  const handleAddressSelect = () => {
    const addresses = allData?.data?.addresses || [];
    const primaryAddress =
      addresses.find((addr: any) => addr.is_primary) || addresses[0] || null;

    const address = primaryAddress || null;

    const { line1, line2 } = buildAddressText(address);

    setSenderAddress(`${line1}${line2}`);
    // setSenderAddress2(line2);

    setPickupAddressId(address.id);
    localStorage.setItem("PICKUP_ADDRESS_ID", String(address.id));

    setErrors((prev) => ({
      ...prev,
      senderAddress: false,
    }));

    // toggleAddressList(); // ✅ close modal
    setShowAddressList(false);
  };

  useEffect(() => {
    const allData = JSON.parse(localStorage.getItem("ALL_DATA") || "{}");
    const addresses = allData?.data?.addresses || [];

    if (!addresses.length) return;

    const primary =
      addresses.find((addr: any) => addr.is_primary) || addresses[0];

    if (primary && !senderAddress) {
      handleAddressSelect();
    }
  }, []);

  // --- Effects ---
  useEffect(() => {
    const fetchCountries = async () => {
      try {
        const response = await getMasterList("country");
        if (response?.status) {
          const countryOptions = response.data.map((c: any) => ({
            value: c.id,
            label: c.name,
            code: c.code ?? c.shortCode,
            name: c.name,
            id: c.id,
          }));
          setCountries(countryOptions);
        }
      } catch (err) {
        console.error("Error fetching countries:", err);
      }
    };
    fetchCountries();
  }, []);

  // When countries or step1 data load, restore sender/receiver country & cities if not already set
  useEffect(() => {
    const restoreFromStep1 = async () => {
      if (!countries || countries.length === 0) return;

      const findCountryMatch = (ref: any) => {
        if (!ref) return null;
        // prefer id/value if available
        const refId = ref.id ?? ref.value ?? null;
        if (refId !== null && refId !== undefined) {
          const byId =
            countries.find((c) => String(c.id) === String(refId)) ||
            countries.find((c) => String(c.value) === String(refId));
          if (byId) return byId;
        }
        // match by code (normalized)
        const refCode = String(ref.code ?? ref.shortCode ?? "").toUpperCase();
        if (refCode) {
          const byCode = countries.find(
            (c) => String(c.code ?? "").toUpperCase() === refCode,
          );
          if (byCode) return byCode;
        }
        // exact name/label match (case-insensitive)
        const refName = (ref.label ?? ref.name ?? "")
          .toString()
          .trim()
          .toLowerCase();
        if (refName) {
          const byName = countries.find(
            (c) =>
              (c.label ?? c.name ?? "").toString().trim().toLowerCase() ===
              refName,
          );
          if (byName) return byName;
        }
        // no loose fallback — return null so caller does not pick wrong country
        return null;
      };

      // restore sender country
      if (!senderCountry && step1Data?.fromCountry) {
        const ref = step1Data.fromCountry;
        const found = findCountryMatch(ref);
        if (found) {
          setSenderCountry(found);
          // fetch cities for this country and try to restore city
          const res = await getInternationalCities({ country_id: found.value });
          if (res?.status) {
            const cityOptions = res.data.map((c: any) => ({
              value: c.id,
              label: c.name,
              name: c.name,
              id: c.id,
            }));
            setSenderCities(cityOptions);
            // restore city if present in step1
            const cityRef = step3Data?.senderCity || step1Data?.fromCity;
            if (cityRef) {
              const cityId =
                (cityRef.id ?? cityRef.value ?? cityRef)?.toString?.() ?? "";
              const foundCity =
                cityOptions.find(
                  (ct: { id: any }) => String(ct.id) === String(cityId),
                ) ||
                cityOptions.find(
                  (ct: { label: any; name: any }) =>
                    (ct.label ?? ct.name ?? "").toString().toLowerCase() ===
                    (cityRef.name ?? "").toString().toLowerCase(),
                );
              if (foundCity) setSenderCity(foundCity);
            }
          }
        }
      }

      // restore receiver country
      if (!receiverCountry && step1Data?.toCountry) {
        const ref = step1Data.toCountry;
        const found = findCountryMatch(ref);
        if (found) {
          setReceiverCountry(found);
          const res = await getInternationalCities({ country_id: found.value });
          if (res?.status) {
            const cityOptions = res.data.map((c: any) => ({
              value: c.id,
              label: c.name,
              name: c.name,
              id: c.id,
            }));
            setReceiverCities(cityOptions);
            const cityRef = step3Data?.receiverCity || step1Data?.toCity;
            if (cityRef) {
              const cityId =
                (cityRef.id ?? cityRef.value ?? cityRef)?.toString?.() ?? "";
              const foundCity =
                cityOptions.find(
                  (ct: { id: any }) => String(ct.id) === String(cityId),
                ) ||
                cityOptions.find(
                  (ct: { label: any; name: any }) =>
                    (ct.label ?? ct.name ?? "").toString().toLowerCase() ===
                    (cityRef.name ?? "").toString().toLowerCase(),
                );
              if (foundCity) setReceiverCity(foundCity);
            }
          }
        }
      }
    };
    // fire without blocking render
    restoreFromStep1().catch((e) => console.error("restoreFromStep1", e));
    console.log(allData, "ds");
    setSenderCompanyName(allData?.data?.companyName);
    setSenderName(step3Data?.senderName ? step3Data?.senderName : `${allData?.data?.altFirstName} ${allData?.data?.altLastName}` || "");
    setSenderEmail(allData?.data?.email);
    setSenderPhone(allData?.data?.phone);
    setSenderAltPhone(allData?.data?.altPhone);
  }, [countries, step1Data]);

  // helper to fetch cities
  const fetchCitiesFor = async (
    country: OptionType | null,
    setCities: React.Dispatch<React.SetStateAction<OptionType[]>>,
  ) => {
    if (!country) {
      setCities([]);
      return;
    }
    try {
      const response = await getInternationalCities({
        country_id: country.value,
      });
      if (response?.status) {
        setCities(
          response.data.map((c: any) => ({
            value: c.id,
            label: c.name,
            name: c.name,
            id: c.id,
          })),
        );
        // if we have step1 data city matching this country, restore it
        // (keep this quick and defensive)
        if (country === senderCountry && step1Data?.fromCity) {
          const found = response.data.find(
            (ct: any) =>
              ct.id ===
                (step3Data?.senderCity?.value ?? step1Data?.fromCity?.value) ||
              ct.name ===
                (step3Data?.senderCity?.name ?? step1Data?.fromCity?.name),
          );
          if (found) {
            setSenderCity({
              value: found.id,
              label: found.name,
              id: found.id,
              name: found.name,
            });
          }
        }
        if (country === receiverCountry && step1Data?.toCity) {
          const found = response.data.find(
            (ct: any) =>
              ct.id ===
                (step3Data?.receiverCity?.value ?? step1Data?.toCity?.value) ||
              ct.name ===
                (step3Data?.receiverCity?.name ?? step1Data?.toCity?.name),
          );
          if (found) {
            setReceiverCity({
              value: found.id,
              label: found.name,
              id: found.id,
              name: found.name,
            });
          }
        }
      } else {
        setCities([]);
      }
    } catch (err) {
      console.error("Error fetching cities:", err);
      setCities([]);
    }
  };

  useEffect(() => {
    fetchCitiesFor(senderCountry, setSenderCities);
  }, [senderCountry]);

  useEffect(() => {
    fetchCitiesFor(receiverCountry, setReceiverCities);
  }, [receiverCountry]);

  // --- Handlers ---
  const handleClearSender = () => {
    setSenderCompanyName("");
    setSenderName("");
    setSenderTaxId("");
    // Keep country/city as they are likely correct from Step 1
    setSenderPostalCode("");
    setSenderPhone("");
    setSenderAltPhone("");
    setSenderEmail("");
    setSenderAddress("");
    setSenderAddress2("");
  };

  const handleClearReceiver = () => {
    setReceiverCompanyName("");
    setReceiverName("");
    setReceiverTaxId("");
    // Keep country/city as they are likely correct from Step 1
    setReceiverPostalCode("");
    setReceiverPhone("");
    setReceiverAltPhone("");
    setReceiverEmail("");
    setReceiverAddress("");
    setReceiverAddress2("");
  };

  const validateStep3 = async () => {
    if (isLoading) return false;

    if (!step1Data) return false;

    const newErrors: Step3Errors = {
      senderCompanyName: !senderCompanyName,
      senderName: !senderName,
      senderPhone: !senderPhone,
      senderAddress: !senderAddress,
      senderCountry: !senderCountry,
      senderCity: !senderCity,
      senderPostalCode: !senderPostalCode,

      receiverCompanyName: !receiverCompanyName,
      receiverName: !receiverName,
      receiverPhone: !receiverPhone,
      receiverAddress: !receiverAddress,
      receiverCountry: !receiverCountry,
      receiverCity: !receiverCity,
      receiverPostalCode: !receiverPostalCode,
    };

    setErrors(newErrors);

    const hasError = Object.values(newErrors).some(Boolean);
    if (hasError) return false;
    if (isLoading) return false; // prevent duplicate submissions

    // ensure step1 exists
    if (!step1Data) {
      window.alert("Please complete Step 1 before proceeding.");
      return false;
    }

    // Basic validation
    if (
      !senderCompanyName ||
      !senderName ||
      !senderPhone ||
      !senderAddress ||
      !senderCountry ||
      !senderCity ||
      !senderPostalCode ||
      !receiverCompanyName ||
      !receiverName ||
      !receiverPhone ||
      !receiverAddress ||
      !receiverCountry ||
      !receiverCity ||
      !receiverPostalCode
    ) {
      window.alert("Please fill all required fields in From and To sections.");
      return false;
    }

    const step1 = JSON.parse(
      localStorage.getItem("CREATE_INTL_STEP1") || "null",
    );
    const allData = JSON.parse(localStorage.getItem("ALL_DATA") || "{}");

    const addresses = allData?.data?.addresses || [];
    const primaryAddress =
      addresses.find((addr: any) => addr.is_primary) || addresses[0] || null;
    const payloadBody = {
      // Step 1: Draft & Package Info
      draft_order_id: step1Data.draft_order_id,
      package_details: (step1?.package_details || []).map((pkg: any) => ({
        package_type_id: pkg.package_type_id ?? undefined,
        weight: parseFloat(pkg.weight || 0),
        length: parseFloat(pkg.length || 0),
        width: parseFloat(pkg.width || 0),
        height: parseFloat(pkg.height || 0),
        package_description: pkg.package_description || undefined,
        customer_input_package_value: parseFloat(
          pkg.customer_input_package_value || 0,
        ),
      })),
      customer_input_order_id: step1Data.customerInputOrderId || undefined,
      description: step1Data.shipmentContent || undefined,
      no_of_packages: step1Data.noOfPackages ?? undefined,
      total_weight: step1Data.totalWeight ?? undefined,
      total_value: step1Data.totalValue ?? undefined,
      pickup_address_id: primaryAddress?.id,
      // Step 2: Carrier / Service
      carrier: createOrderData.step2?.selectedCarrierDetails?.name || undefined,
      service_code:
        createOrderData.step2?.selectedServiceDetails?.id || undefined,
      service_name:
        createOrderData.step2?.selectedServiceDetails?.name || undefined,
      shipping_charge:
        createOrderData.step2?.selectedServiceDetails?.price ?? undefined,
      currency:
        createOrderData.step2?.selectedServiceDetails?.currency ?? undefined,

      // Step 3: Sender Info
      shipper_name: senderName || undefined,
      pickup_customer_name: senderName || undefined,
      shipper_company_name: senderCompanyName || undefined,
      shipper_email: senderEmail || undefined,
      pickup_mobile_number: senderPhone || undefined,
      pickup_alternate_number: senderAltPhone || undefined,
      shipper_address: senderAddress || undefined,
      shipper_address_2: senderAddress2 || undefined,
      shipper_city_id: senderCity?.value || undefined,
      shipper_city: senderCity?.label || undefined,
      shipper_postal_code: senderPostalCode || undefined,
      shipper_country_id:
        senderCountry?.value || step1Data?.fromCountry?.value || undefined,
      shipper_country:
        senderCountry?.label || step1Data?.fromCountry?.label || undefined,
      shipper_tax_no: senderTaxId || undefined,
      // Step 3: Receiver Info
      recipient_name: receiverName || undefined,
      destination_customer_name: receiverName || undefined,
      recipient_company_name: receiverCompanyName || undefined,
      recipient_email: receiverEmail || undefined,
      destination_mobile_number: receiverPhone || undefined,
      destination_alternate_number: receiverAltPhone || undefined,
      recipient_address: receiverAddress || undefined,
      recipient_address_2: receiverAddress2 || undefined,
      recipient_city_id: receiverCity?.value || undefined,
      recipient_city: receiverCity?.label || undefined,
      recipient_postal_code: receiverPostalCode || undefined,
      recipient_country_id:
        receiverCountry?.value || step1Data?.toCountry?.value || undefined,
      recipient_country:
        receiverCountry?.label || step1Data?.toCountry?.label || undefined,
      recipient_tax_no: receiverTaxId || undefined,
      // Step 4: Pickup & Reference
      // pickup_address_id: step4Data?.pickup_address_id || undefined,
      // pickup_customer_name: step4Data?.pickup_customer_name || undefined,
      // pickup_mobile_number: step4Data?.pickup_mobile_number || undefined,
      // pickup_alternate_number: step4Data?.pickup_alternate_number || undefined,
      delivery_instructions: step4Data?.delivery_instructions || undefined,
      pickup_date: step4Data?.pickup_date
        ? new Date(step4Data.pickup_date)
        : undefined,
      pickup_slot_type: step4Data?.pickup_slot_type ?? undefined,
      ref_order_id: step1Data.ref_order_id || undefined,

      // Optional Customs / COD
      payment_type: step1Data.paymentType || undefined,
      customs_value: step1Data.totalValue || undefined,
      is_cod: step1Data.isCod ?? undefined,
      cod_amount: step1Data.codAmount ?? undefined,
      product_group: step1Data.productGroup || undefined,
      product_type: step1Data.productType || undefined,
    };

    try {
      setIsLoading(true);
      const response = await initiateInternationalDraftOrder(payloadBody);
      if (response?.status) {
        // pass saved values back (include API response if useful)
        onSave({
          senderCompanyName,
          senderName,
          senderTaxId,
          senderCountry,
          senderCity,
          senderPostalCode,
          senderPhone,
          senderAltPhone,
          senderEmail,
          senderAddress,
          senderAddress2,
          saveSender,
          receiverCompanyName,
          receiverName,
          receiverTaxId,
          receiverCountry,
          receiverCity,
          receiverPostalCode,
          receiverPhone,
          receiverAltPhone,
          receiverEmail,
          receiverAddress,
          receiverAddress2,
          saveReceiver,
          apiResponse: response.data ?? null,
        });
        return true;
      } else {
        console.error("Failed to update draft:", response?.message);
        Swal.fire({
          icon: "error",
          title: "Failed to update order details",
          text: response?.message || "Something went wrong. Please try again.",
          customClass: {
            confirmButton: "delybell-primary px-4",
            cancelButton: "delybell-dark",
          },
        });
        return false;
      }
    } catch (error) {
      console.error("Error updating draft:", error);
      Swal.fire({
        icon: "error",
        title: "Failed to update order details",
        text: "An error occurred while updating draft. Please try again.",
        customClass: {
          confirmButton: "delybell-primary px-4",
          cancelButton: "delybell-dark",
        },
      });
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  const toggleAddressList = () => {
    setShowAddressList((prev) => !prev);
    // handleAddressSelect()
  };
  useEffect(() => {
    // When modal is CLOSED, refresh latest address
    if (!showAddressList) {
      handleAddressSelect();
    }
  }, [showAddressList]);

  return (
    <>
      {isLoading && <HourGlassLoader />}
      <div className="scrollWrap step3-international p-4">
        <div className="row g-4">
          {/* Sender Section (From) */}
          <div className="col-lg-6 border-end-lg">
            <div className="d-flex justify-content-between align-items-center mb-4">
              <h5 className="font-16 font-700 mb-0">From</h5>
              <button
                className="btn btn-link text-danger text-decoration-none font-12 font-600 p-0"
                onClick={handleClearSender}
                type="button"
              >
                <i className="ri-refresh-line me-1"></i> Clear Address
              </button>
            </div>

            <div className="row g-3">
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Company Name <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-building-2-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.senderCompanyName ? "is-invalid" : ""
                      }`}
                      value={senderCompanyName}
                      onChange={(e) => setSenderCompanyName(e.target.value)}
                      placeholder="Company Name"
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Name <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-user-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.senderName ? "is-invalid" : ""
                      }`}
                      value={senderName}
                      onChange={(e) => setSenderName(e.target.value)}
                      placeholder="Name"
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Country <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-global-fill text-dark-blue font-18"></i>
                    <SelectOptions
                      name="senderCountry"
                      optionsData={countries}
                      value={senderCountry}
                      isDisabled
                      onChange={(val: any) => setSenderCountry(val)}
                      placeholder="Select Country"
                      divClassName="mb-0"
                      style={{
                        control: (base: any) => ({
                          ...base,
                          borderRadius: "10px",
                          height: "45px",
                          paddingLeft: "35px",
                          border: errors.senderCountry
                            ? "1px solid #dc3545"
                            : "1px solid #dee2e6",
                          boxShadow: "none",
                        }),
                      }}
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    City <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-building-fill text-dark-blue font-18"></i>
                    <SelectOptions
                      name="senderCity"
                      optionsData={senderCities}
                      value={senderCity}
                      onChange={(val: any) => setSenderCity(val)}
                      placeholder="Select City"
                      divClassName="mb-0"
                      style={{
                        control: (base: any) => ({
                          ...base,
                          borderRadius: "15px",
                          height: "50px",
                          paddingLeft: "40px",
                          border: errors.senderCity
                            ? "1px solid #dc3545"
                            : "1px solid #dee2e6",
                          boxShadow: "none",
                          "&:hover": {
                            borderColor: errors.senderCity
                              ? "#dc3545"
                              : "#dee2e6",
                          },
                        }),
                      }}
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Postal Code <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-mailbox-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.senderPostalCode ? "is-invalid" : ""
                      }`}
                      value={senderPostalCode}
                      onChange={(e) => setSenderPostalCode(e.target.value)}
                      placeholder="Postal Code"
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Tax ID/VAT/EIN Number
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-file-list-3-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.senderTaxId ? "is-invalid" : ""
                      }`}
                      value={senderTaxId}
                      onChange={(e) => setSenderTaxId(e.target.value)}
                      placeholder="Tax ID/VAT/EIN Number"
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Mobile Number <RequiredStar />
                  </label>
                  <div className="phone-input-wrapper">
                    <InternationalPhoneInput
                      value={senderPhone}
                      onChange={(val: string) => setSenderPhone(val)}
                      className={`form-control custom-input-rounded ${
                        errors.senderPhone ? "is-invalid" : ""
                      }`}
                      placeholder="Mobile Number"
                      country={resolveCountryCode(senderCountry, countries)}
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Alternative Mobile Number
                  </label>
                  <div className="phone-input-wrapper">
                    <InternationalPhoneInput
                      value={senderAltPhone}
                      onChange={(val: string) => setSenderAltPhone(val)}
                      className={`form-control custom-input-rounded ${
                        errors.senderAltPhone ? "is-invalid" : ""
                      }`}
                      placeholder="Alternative Mobile Number"
                      country={resolveCountryCode(senderCountry, countries)}
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-12">
                <div className="floating-label-group">
                  <label className="floating-label">Email Address</label>
                  <div className="input-with-icon">
                    <i className="ri-mail-fill text-dark-blue font-18"></i>
                    <input
                      type="email"
                      className={`form-control custom-input-rounded ${
                        errors.senderEmail ? "is-invalid" : ""
                      }`}
                      value={senderEmail}
                      onChange={(e) => setSenderEmail(e.target.value)}
                      placeholder="Email Address"
                    />
                  </div>
                </div>
              </div>

              {/* <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Address Line 1 <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-home-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.senderAddress ? "is-invalid" : ""
                      }`}
                      value={senderAddress}
                      onChange={(e) => setSenderAddress(e.target.value)}
                      placeholder="Address Line 1"
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">Address Line 2</label>
                  <div className="input-with-icon">
                    <i className="ri-home-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.senderAddress2 ? "is-invalid" : ""
                      }`}
                      value={senderAddress2}
                      onChange={(e) => setSenderAddress2(e.target.value)}
                      placeholder="Address Line 2"
                    />
                  </div>
                </div>
              </div> */}
              <div className="col-md-12">
                <div className="floating-label-group has-value">
                  <label className="floating-label">
                    Address <RequiredStar />
                  </label>

                  <div className="address-input-wrapper">
                    {/* LEFT icon */}
                    <i className="ri-home-fill left-icon" />

                    {/* Text input */}
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.senderAddress ? "is-invalid" : ""
                      }`}
                      disabled
                      value={senderAddress}
                      onChange={(e) => setSenderAddress(e.target.value)}
                      placeholder="Address"
                    />

                    {/* RIGHT edit icon */}
                    <i
                      className="ri-pencil-line right-icon"
                      title="Edit address"
                      onClick={toggleAddressList}
                    />
                  </div>
                </div>
              </div>

              {/* <div className="col-12 mt-2">
                <div className="form-check">
                  <input
                    className="form-check-input"
                    type="checkbox"
                    id="saveSender"
                    checked={saveSender}
                    onChange={(e) => setSaveSender(e.target.checked)}
                  />
                  <label
                    className="form-check-label font-13 text-muted"
                    htmlFor="saveSender"
                  >
                    Save this to my address book.
                  </label>
                </div>
              </div> */}
            </div>
          </div>

          {/* Receiver Section (To) */}
          <div className="col-lg-6">
            <div className="d-flex justify-content-between align-items-center mb-4">
              <h5 className="font-16 font-700 mb-0">To</h5>
              <button
                className="btn btn-link text-danger text-decoration-none font-12 font-600 p-0"
                onClick={handleClearReceiver}
                type="button"
              >
                <i className="ri-refresh-line me-1"></i> Clear Address
              </button>
            </div>

            <div className="row g-3">
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Company Name <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-building-2-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.receiverCompanyName ? "is-invalid" : ""
                      }`}
                      value={receiverCompanyName}
                      onChange={(e) => setReceiverCompanyName(e.target.value)}
                      placeholder="Company Name"
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Name <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-user-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.receiverName ? "is-invalid" : ""
                      }`}
                      value={receiverName}
                      onChange={(e) => setReceiverName(e.target.value)}
                      placeholder="Name"
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Country <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-global-fill text-dark-blue font-18"></i>
                    <SelectOptions
                      name="receiverCountry"
                      optionsData={countries}
                      value={receiverCountry}
                      onChange={(val: any) => setReceiverCountry(val)}
                      placeholder="Select Country"
                      divClassName="mb-0"
                      style={{
                        control: (base: any) => ({
                          ...base,
                          borderRadius: "10px",
                          height: "45px",
                          paddingLeft: "35px",
                          border: errors.receiverCountry
                            ? "1px solid #dc3545"
                            : "1px solid #dee2e6",
                          boxShadow: "none",
                        }),
                      }}
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    City <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-building-fill text-dark-blue font-18"></i>
                    <SelectOptions
                      name="receiverCity"
                      optionsData={receiverCities}
                      value={receiverCity}
                      onChange={(val: any) => setReceiverCity(val)}
                      placeholder="Select City"
                      divClassName="mb-0"
                      style={{
                        control: (base: any) => ({
                          ...base,
                          borderRadius: "10px",
                          height: "45px",
                          paddingLeft: "35px",
                          border: errors.receiverCity
                            ? "1px solid #dc3545"
                            : "1px solid #dee2e6",
                          boxShadow: "none",
                        }),
                      }}
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Postal Code <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-mailbox-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.receiverPostalCode ? "is-invalid" : ""
                      }`}
                      value={receiverPostalCode}
                      onChange={(e) => setReceiverPostalCode(e.target.value)}
                      placeholder="Postal Code"
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Tax ID/VAT/EIN Number
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-file-list-3-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.receiverTaxId ? "is-invalid" : ""
                      }`}
                      value={receiverTaxId}
                      onChange={(e) => setReceiverTaxId(e.target.value)}
                      placeholder="Tax ID/VAT/EIN Number"
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Mobile Number <RequiredStar />
                  </label>
                  <div className="phone-input-wrapper">
                    <InternationalPhoneInput
                      value={receiverPhone}
                      onChange={(val: string) => setReceiverPhone(val)}
                      placeholder="Mobile Number"
                      className={`form-control custom-input-rounded ${
                        errors.receiverPhone ? "is-invalid" : ""
                      }`}
                      country={resolveCountryCode(receiverCountry, countries)}
                    />
                  </div>
                </div>
              </div>
              <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Alternative Mobile Number
                  </label>
                  <div className="phone-input-wrapper">
                    <InternationalPhoneInput
                      value={receiverAltPhone}
                      onChange={(val: string) => setReceiverAltPhone(val)}
                      className={`form-control custom-input-rounded ${
                        errors.receiverAltPhone ? "is-invalid" : ""
                      }`}
                      placeholder="Alternative Mobile Number"
                      country={resolveCountryCode(receiverCountry, countries)}
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-12">
                <div className="floating-label-group">
                  <label className="floating-label">Email Address</label>
                  <div className="input-with-icon">
                    <i className="ri-mail-fill text-dark-blue font-18"></i>
                    <input
                      type="email"
                      className={`form-control custom-input-rounded ${
                        errors.receiverEmail ? "is-invalid" : ""
                      }`}
                      value={receiverEmail}
                      onChange={(e) => setReceiverEmail(e.target.value)}
                      placeholder="Email Address"
                    />
                  </div>
                </div>
              </div>

              <div className="col-md-12">
                <div className="floating-label-group">
                  <label className="floating-label">
                    Address <RequiredStar />
                  </label>
                  <div className="input-with-icon">
                    <i className="ri-home-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.receiverAddress ? "is-invalid" : ""
                      }`}
                      value={receiverAddress}
                      onChange={(e) => setReceiverAddress(e.target.value)}
                      placeholder="Address"
                    />
                  </div>
                </div>
              </div>
              {/* <div className="col-md-6">
                <div className="floating-label-group">
                  <label className="floating-label">Address Line 2</label>
                  <div className="input-with-icon">
                    <i className="ri-home-fill text-dark-blue font-18"></i>
                    <input
                      type="text"
                      className={`form-control custom-input-rounded ${
                        errors.receiverAddress2 ? "is-invalid" : ""
                      }`}
                      value={receiverAddress2}
                      onChange={(e) => setReceiverAddress2(e.target.value)}
                      placeholder="Address Line 2"
                    />
                  </div>
                </div>
              </div> */}

              {/* <div className="col-12 mt-2">
                <div className="form-check">
                  <input
                    className="form-check-input"
                    type="checkbox"
                    id="saveReceiver"
                    checked={saveReceiver}
                    onChange={(e) => setSaveReceiver(e.target.checked)}
                  />
                  <label
                    className="form-check-label font-13 text-muted"
                    htmlFor="saveReceiver"
                  >
                    Save this to my address book.
                  </label>
                </div>
              </div> */}
            </div>
          </div>
        </div>
      </div>
      {/* ADDRESS PREVIEW SECTION */}
      {/* <div className="address-preview-section mt-4">
  <h6 className="font-14 font-700 mb-3">Address Preview</h6>

  <div className="row g-3">
    <div className="col-md-6">
      <div className="preview-card">
        <div className="preview-header">
          <i className="ri-upload-2-line"></i>
          <span>From</span>
        </div>

        <div className="preview-body">
          <p className="preview-name">{senderName || "—"}</p>
          <p>{senderAddress || "—"}</p>
          {senderAddress2 && <p>{senderAddress2}</p>}
          <p>
            {senderCity?.label || ""}{" "}
            {senderPostalCode && `- ${senderPostalCode}`}
          </p>
          <p>{senderCountry?.label || ""}</p>
          <p className="preview-phone">{senderPhone || ""}</p>
        </div>
      </div>
    </div>

    <div className="col-md-6">
      <div className="preview-card">
        <div className="preview-header">
          <i className="ri-download-2-line"></i>
          <span>To</span>
        </div>

        <div className="preview-body">
          <p className="preview-name">{receiverName || "—"}</p>
          <p>{receiverAddress || "—"}</p>
          {receiverAddress2 && <p>{receiverAddress2}</p>}
          <p>
            {receiverCity?.label || ""}{" "}
            {receiverPostalCode && `- ${receiverPostalCode}`}
          </p>
          <p>{receiverCountry?.label || ""}</p>
          <p className="preview-phone">{receiverPhone || ""}</p>
        </div>
      </div>
    </div>
  </div>
</div> */}

      <CreateOrderFooter
        step={step}
        setStep={async (nextStep) => {
          if (await validateStep3()) setStep(nextStep);
        }}
        validation={validateStep3}
        backButton={true}
        // Navigate explicitly to Step 2 and notify listeners so Step2 can reload selected package/service.
        backButtonFn={() => {
          setStep(2);
          try {
            // Emit event so Step2 can listen and re-populate its selects if necessary.
            // include reload:true so Step2 knows to re-fetch/restore state
            window.dispatchEvent(
              new CustomEvent("navigate-to-step", {
                detail: { step: 2, reload: true },
              }),
            );
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
          } catch (err) {
            // ignore in non-browser environments
          }
        }}
        defaultOrderDetails={defaultOrderDetails}
        isEditMode={isEditMode}
      />
      <Modal
        show={showAddressList}
        onHide={toggleAddressList}
        header={false}
        fullscreen={"md"}
        centered
        position="center"
        classname=""
      >
        <AddressList
          modal
          toggleAddressChange={toggleAddressList}
          // onSelect={handleAddressSelect}
          // selectedAddressId={pickupAddressId}
        />
      </Modal>

      <style jsx>{`
        .font-12 {
          font-size: 12px;
        }
        .font-13 {
          font-size: 13px;
        }
        .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;
        }
        .floating-label-group {
          position: relative;
          margin-top: 5px;
        }
        .floating-label {
          position: absolute;
          top: -10px;
          left: 15px;
          background: white;
          padding: 0 8px;
          font-size: 10px;
          font-weight: 700;
          color: #adb5bd;
          z-index: 10;
          pointer-events: none;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
        .input-with-icon {
          position: relative;
        }
        .input-with-icon i {
          position: absolute;
          left: 15px;
          top: 50%;
          transform: translateY(-50%);
          z-index: 5;
          color: #000080;
        }
        .custom-input-rounded {
          padding-left: 40px !important;
          border-radius: 10px !important;
          height: 45px !important;
          border: 1px solid #dee2e6 !important;
        }
        .custom-input-rounded:focus {
          border-color: #000080 !important;
          box-shadow: 0 0 0 0.25rem rgba(0, 0, 128, 0.1) !important;
        }
        .border-end-lg {
          border-right: 1px solid #dee2e6;
        }
        @media (max-width: 991px) {
          .border-end-lg {
            border-right: none;
            border-bottom: 1px solid #dee2e6;
            padding-bottom: 1.5rem;
            margin-bottom: 1.5rem;
          }
        }
        .is-invalid {
          border-color: #dc3545 !important;
        }
        /* Phone input wrapper: keep simple and rely on phone component for layout */
        .phone-input-wrapper {
          position: relative;
        }
        /* phone inputs: smaller left padding so flag/dial-code sits inside the border */
        .phone-input-wrapper .custom-input-rounded {
          padding-left: 12px !important; /* smaller gap for flag */
          height: 45px !important;
          display: flex;
          align-items: center;
        }
        /* make phone input show the same focus ring as other inputs */
        .phone-input-wrapper .custom-input-rounded:focus-within {
          border-color: #000080 !important;
          box-shadow: 0 0 0 0.25rem rgba(0, 0, 128, 0.08) !important;
        }
        .edit-icon {
          position: absolute;
          right: 12px;
          top: 50%;
          transform: translateY(-50%);
          font-size: 16px;
          color: #000080;
          cursor: pointer;
          z-index: 6;
        }
        .input-style.has-icon.has-borders
          .phone-input-country
          input.PhoneInputInput {
          padding-left: 0 !important;
        }
        .address-input-wrapper {
          position: relative;
        }

        /* Left icon */
        .address-input-wrapper .left-icon {
          position: absolute;
          left: 14px;
          top: 50%;
          transform: translateY(-50%);
          font-size: 16px;
          color: #000080;
          z-index: 5;
        }

        /* Right edit icon */
        .address-input-wrapper .right-icon {
          position: absolute;
          right: 14px;
          top: 50%;
          transform: translateY(-50%);
          font-size: 16px;
          color: #000080;
          cursor: pointer;
          z-index: 5;
        }

        .address-input-wrapper .right-icon:hover {
          color: #0d6efd;
        }

        /* Ensure padding for icons */
        .address-input-wrapper input.custom-input-rounded {
          padding-left: 40px !important;
          padding-right: 40px !important;
        }
        .address-preview-section {
          background: #f8f9fa;
          border-radius: 12px;
          padding: 16px;
        }

        .preview-card {
          background: #ffffff;
          border-radius: 12px;
          padding: 14px;
          border: 1px solid #dee2e6;
          height: 100%;
        }

        .preview-header {
          display: flex;
          align-items: center;
          gap: 8px;
          font-weight: 700;
          font-size: 13px;
          color: #000080;
          margin-bottom: 10px;
        }

        .preview-header i {
          font-size: 16px;
        }

        .preview-body p {
          margin-bottom: 4px;
          font-size: 13px;
          color: #495057;
        }

        .preview-name {
          font-weight: 700;
          color: #212529;
        }

        .preview-phone {
          font-weight: 600;
          color: #000;
        }

        .floating-label-group.has-value .floating-label,
        .floating-label-group input:focus + .floating-label {
          top: -8px;
          font-size: 11px;
          color: #495057;
        }
      `}</style>
    </>
  );
};

export default Step3;
