/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useState, useMemo } from "react";
import CreateOrderFooter from "./CreateOrderFooter";
import PackageGrid from "./Step1/PackageGrid";
import SelectOptions, { OptionType } from "../../../TextField/SelectOptions";
import {
  getMasterList,
  // getInternationalCities,
} from "../../../../Api/MastersApi";
import Step1Skeleton from "./Step1/Step1Skeleton";
import { initiateInternationalDraftOrder } from "../../../../Api/InternationalOrderApi";

import { useAppSelector } from "@/Redux/Hooks";
import RequiredStar from "./RequiredStar";
import { useCurrency } from "@/context/CurrencyContext";

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

interface PackageDetail {
  weight: string;
  length: string;
  width: string;
  height: string;
  package_description: string;
  customer_input_package_value: string;
}

const Step1: React.FC<Step1Props> = ({
  onSave,
  step,
  setStep,
  defaultOrderDetails,
  isEditMode,
}) => {
    const { currencyName } = useCurrency();

  const [isLoading, setIsLoading] = useState<boolean>(false);
  const createOrderData: any = useAppSelector(
    (state) => state.createOrder,
  )?.step1;
  const [step1Data, setStep1Data] = useState(createOrderData?.step1 || {}); // Store step1 data in local state

  const [fromCountry, setFromCountry] = useState<OptionType | null>(null);
  const [toCountry, setToCountry] = useState<OptionType | null>(null);
  const [fromCity, setFromCity] = useState<OptionType | null>(null);
  const [toCity, setToCity] = useState<OptionType | null>(null);

  const [shipmentContent, setShipmentContent] = useState<"Document" | "Parcel">(
    "Parcel",
  );
  const [noOfPackages, setNoOfPackages] = useState<number>(1);
  const [defaultPackageWeight, setDefaultPackageWeight] = useState<string>("");
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [defaultPackageValue, setDefaultPackageValue] = useState<string>("");
  const [defaultPackageDescription, setDefaultPackageDescription] =
    useState<string>("");
  const [packageDetails, setPackageDetails] = useState<PackageDetail[]>([
    {
      weight: "",
      length: "",
      width: "",
      height: "",
      package_description: "",
      customer_input_package_value: "",
    },
  ]);

  const [countries, setCountries] = useState<OptionType[]>([]);

  // Validation errors state
  const [errors, setErrors] = useState<{
    fromCountry?: string;
    toCountry?: string;
    fromCity?: string;
    toCity?: string;
    packageDetails?: { [key: number]: { [field: string]: string } };
  }>({});

  // Helper: persist step1 data locally
  const persistStep1Local = (data: any) => {
    try {
      localStorage.setItem("CREATE_INTL_STEP1", JSON.stringify(data));
    } catch (err) {
      console.error("Failed to persist step1:", err);
    }
  };

  // Helper: read persisted step1 data (fallback)
  const readPersistedStep1 = (): any => {
    try {
      return JSON.parse(localStorage.getItem("CREATE_INTL_STEP1") || "null");
    } catch {
      return null;
    }
  };

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

          // Set default From Country to Bahrain if available
          // const bahrain = countryOptions.find(
          //   (c: any) => c.code === "BH" || c.name === "Bahrain",
          // );
          // if (bahrain) setFromCountry(bahrain);

          // Try to restore persisted / redux selections AFTER countries loaded
          // Logic moved to separate useEffect to avoid dependency loop
        }
      } catch (err) {
        console.error("Error fetching countries:", err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchCountries();
  }, []); // Run only on mount

  // Restore selections when countries are loaded or createOrderData changes
  useEffect(() => {
    if (countries.length > 0 && (createOrderData || readPersistedStep1())) {
      const persisted = readPersistedStep1() || createOrderData || null;

      // Only restore if not already set (to avoid overwriting user changes if they happen before this runs)
      // Or if we want to force sync, we should be careful.
      // For now, let's assume if state is null, we try to restore.

      if (!fromCountry) {
        const persistedFromId =
          persisted?.fromCountry?.value ||
          persisted?.fromCountry?.id ||
          persisted?.shipper_country_details?.id ||
          persisted?.shipperCountryId;
        if (persistedFromId) {
          const match = countries.find(
            (co: any) => co.value === persistedFromId,
          );
          if (match) setFromCountry(match);
        } else {
          // Default to Bahrain if nothing persisted and not set
          const bahrain = countries.find(
            (c: any) => c.code === "BH" || c.name === "Bahrain",
          );
          if (bahrain) setFromCountry(bahrain);
        }
      }

      if (!toCountry) {
        const persistedToId =
          persisted?.toCountry?.value ||
          persisted?.toCountry?.id ||
          persisted?.recipient_country_details?.id ||
          persisted?.recipientCountryId;
        if (persistedToId) {
          const match = countries.find((co: any) => co.value === persistedToId);
          if (match) setToCountry(match);
        }
      }
    }
  }, [countries, createOrderData, fromCountry, toCountry]);
  const step1 = JSON.parse(localStorage.getItem("CREATE_INTL_STEP1") || "null");

  // Initialize from redux/createOrder data
  useEffect(() => {
    if (createOrderData) {
      // Set initial values
      if (createOrderData.fromCountry)
        setFromCountry(createOrderData.fromCountry);
      if (createOrderData.toCountry) setToCountry(createOrderData.toCountry);
      if (createOrderData.fromCity) setFromCity(createOrderData.fromCity);
      if (createOrderData.toCity) setToCity(createOrderData.toCity);
      if (createOrderData.shipmentContent)
        setShipmentContent(createOrderData.shipmentContent);
      if (createOrderData.noOfPackages)
        setNoOfPackages(createOrderData.noOfPackages);
      if (createOrderData.packageDetails)
        setPackageDetails(createOrderData.packageDetails);
      else if (createOrderData.package_details)
        setPackageDetails(createOrderData.package_details);
      if (step1) {
        setFromCountry(step1.fromCountry);
        setToCountry(step1.toCountry);
        setFromCity(step1.fromCity);
        setToCity(step1.toCity);
        setShipmentContent(step1.shipmentContent);
        setNoOfPackages(step1.noOfPackages);
        setPackageDetails(step1.package_details);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [createOrderData]);

  // Load default package value from localStorage
  useEffect(() => {
    try {
      const allData = JSON.parse(localStorage.getItem("ALL_DATA") || "{}");
      const packageDescription = allData?.data?.packageDescription || "";
      handleDefaultDescriptionChange(packageDescription);
    } catch (error) {
      console.error("Error loading default package value:", error);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const totalWeight = useMemo(() => {
    return packageDetails.reduce(
      (sum, pkg) => sum + (parseFloat(pkg?.weight) || 0),
      0,
    );
  }, [packageDetails]);

  const totalValue = useMemo(() => {
    return packageDetails.reduce(
      (sum, pkg) => sum + (parseFloat(pkg.customer_input_package_value) || 0),
      0,
    );
  }, [packageDetails]);

  const handlePackagesChange = (val: number) => {
    const count = Math.max(1, val);
    setNoOfPackages(count);
    const updated = [...packageDetails];
    if (count > updated.length) {
      for (let i = updated.length; i < count; i++) {
        updated.push({
          weight: "",
          length: "",
          width: "",
          height: "",
          package_description: "",
          customer_input_package_value: "",
        });
      }
    } else {
      updated.splice(count);
    }
    setPackageDetails(updated);
    onSave({ noOfPackages: count, packageDetails: updated });
  };

  const handleSwap = () => {
    const tempCountry = fromCountry;
    const tempCity = fromCity;

    setFromCountry(toCountry);
    setToCountry(tempCountry);
    setFromCity(toCity);
    setToCity(tempCity);

    onSave({
      fromCountry: toCountry,
      toCountry: tempCountry,
      fromCity: toCity,
      toCity: tempCity,
    });
  };

  const handleDefaultWeightChange = (value: string) => {
    setDefaultPackageWeight(value);
    // Update all package weights
    const updated = packageDetails.map((pkg) => ({
      ...pkg,
      weight: value,
    }));
    setPackageDetails(updated);
    onSave({ defaultPackageWeight: value, packageDetails: updated });
  };
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleDefaultValueChange = (value: string) => {
    setDefaultPackageValue(value);
    // Update all package values
    const updated = packageDetails.map((pkg) => ({
      ...pkg,
      customer_input_package_value: value,
    }));
    setPackageDetails(updated);
    onSave({ defaultPackageValue: value, packageDetails: updated });
  };

  const handleDefaultDescriptionChange = (value: string) => {
    setDefaultPackageDescription(value);
    // Update all package values
    const updated = packageDetails.map((pkg) => ({
      ...pkg,
      package_description: value,
    }));
    setPackageDetails(updated);
    onSave({ defaultPackageDescription: value, packageDetails: updated });
  };

  const validateStep1 = async () => {
    const newErrors: typeof errors = {};

    // Validate countries and cities
    if (!fromCountry) {
      newErrors.fromCountry = "From Country is required";
    }
    if (!toCountry) {
      newErrors.toCountry = "To Country is required";
    }
    if (!fromCity) {
      newErrors.fromCity = "From City is required";
    }
    if (!toCity) {
      newErrors.toCity = "To City is required";
    }

    // Validate package details
    const packageErrors: { [key: number]: { [field: string]: string } } = {};
    packageDetails.forEach((pkg, index) => {
      const pkgErrors: { [field: string]: string } = {};
      if (!pkg.length || parseFloat(pkg.length) <= 0) {
        pkgErrors.length = "Length is required";
      }
      if (!pkg.width || parseFloat(pkg.width) <= 0) {
        pkgErrors.width = "Width is required";
      }
      if (!pkg.height || parseFloat(pkg.height) <= 0) {
        pkgErrors.height = "Height is required";
      }
      if (!pkg.weight || parseFloat(pkg.weight) <= 0) {
        pkgErrors.weight = "Weight is required";
      }
      if (
        !pkg.customer_input_package_value ||
        parseFloat(pkg.customer_input_package_value) <= 0
      ) {
        pkgErrors.customer_input_package_value = "Package value is required";
      }
      if (Object.keys(pkgErrors).length > 0) {
        packageErrors[index] = pkgErrors;
      }
    });

    if (Object.keys(packageErrors).length > 0) {
      newErrors.packageDetails = packageErrors;
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return false;
    }

    setErrors({});
    const allData = JSON.parse(localStorage.getItem("ALL_DATA") || "{}")?.data;

    const payload = {
      created_for_id: allData?.user?.id,
      fromCountry,
      toCountry,
      fromCity,
      toCity,
      shipmentContent,
      noOfPackages,
      package_details: packageDetails,
      total_weight: totalWeight,
      total_value: totalValue,
    };

    try {
      setIsLoading(true);

      // Use existing draft_order_id from state or persisted storage if available
      const persisted = readPersistedStep1();
      const draftOrderId =
        step1Data?.draft_order_id || persisted?.draft_order_id || 0;
      const response = await initiateInternationalDraftOrder({
        ...payload,
        product_type: payload?.shipmentContent,
        draft_order_id: draftOrderId,
        shipper_country_id: fromCountry?.value,
        recipient_country_id: toCountry?.value,
        shipper_city_id: fromCity?.value,
        recipient_city_id: toCity?.value,
      });

      if (response.status) {
        const resData: any = response.data;

        // helpers to map API country/city to OptionType
        const mapCountry = (c: any): OptionType | null =>
          c
            ? {
                value: c.id,
                label: c.name,
                code: c.shortCode || c.code,
                name: c.name,
                id: c.id,
              }
            : null;
        const mapCity = (c: any): OptionType | null =>
          c ? { value: c.id, label: c.name, name: c.name, id: c.id } : null;

        const updatedFromCountry =
          mapCountry(resData.shipper_country_details) || fromCountry;
        const updatedToCountry =
          mapCountry(resData.recipient_country_details) || toCountry;
        const updatedFromCity =
          mapCity(resData.shipper_city_details) || fromCity;
        const updatedToCity = mapCity(resData.recipient_city_details) || toCity;

        // Map draft_order_package_list to local package structure if provided
        const updatedPackages: PackageDetail[] = Array.isArray(
          resData.draft_order_package_list,
        )
          ? resData.draft_order_package_list.map((p: any) => ({
              weight: p.weight ?? "",
              length: p.length ?? "",
              width: p.width ?? "",
              height: p.height ?? "",
              package_description: p.packageDescription ?? "",
              customer_input_package_value: p.customerInputPackageValue ?? "",
            }))
          : packageDetails;

        const updatedStep1Data = {
          ...payload,
          draft_order_id: resData.id, // Update draft_order_id with the response
          fromCountry: updatedFromCountry,
          toCountry: updatedToCountry,
          fromCity: updatedFromCity,
          toCity: updatedToCity,
          package_details: updatedPackages,
          // keep also raw ids for safer restore
          shipperCityId:
            resData.shipperCityId ?? resData.shipper_city_details?.id,
          recipientCityId:
            resData.recipientCityId ?? resData.recipient_city_details?.id,
        };

        // Update component state so UI shows country/city & packages from response
        setStep1Data(updatedStep1Data);
        setFromCountry(updatedFromCountry);
        setToCountry(updatedToCountry);
        setFromCity(updatedFromCity);
        setToCity(updatedToCity);
        setPackageDetails(updatedPackages);

        // persist for future fallback
        persistStep1Local(updatedStep1Data);

        onSave(updatedStep1Data); // Save the updated data
        return true;
      } else {
        setErrors({
          fromCountry: "Failed to initiate order. Please try again.",
        });
        return false;
      }
    } catch (error) {
      console.error("Error initiating draft:", error);
      setErrors({ fromCountry: "An error occurred. Please try again." });
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  console.log(packageDetails, "packageDetails");

  if (isLoading) {
    return <Step1Skeleton />;
  }

  return (
    <>
      <div className="scrollWrap step1-international p-4 bg-white">
        <div className="row g-4">
          {/* Left Sidebar - Receipt Style Preview */}
          <div className="col-lg-3">
            <div className="receipt-sidebar shadow-sm">
              <div className="receipt-content p-4">
                <div className="text-center mb-4">
                  <h6 className="font-14 font-700 mb-3 text-dark">
                    Preview Details
                  </h6>
                  <div className="d-flex align-items-center justify-content-center gap-2 mb-3">
                    <h6 className="font-13 font-600 mb-0 text-dark">
                      {fromCountry?.name || "Bahrain"}
                    </h6>
                    <i className="ri-arrow-right-line font-14 text-purple"></i>
                    <h6 className="font-13 font-600 mb-0 text-dark">
                      {toCountry?.name || "Select Country"}
                    </h6>
                  </div>
                  {fromCity && toCity && (
                    <p className="font-11 text-muted mb-0">
                      {fromCity.name} → {toCity.name}
                    </p>
                  )}
                </div>

                <div className="preview-details">
                  <div className="preview-row">
                    <span className="preview-label">Package Type</span>
                    <span className="preview-value">{shipmentContent}</span>
                  </div>
                  <hr className="my-2" />

                  <div className="preview-row">
                    <span className="preview-label">No. of Packages</span>
                    <span className="preview-value">
                      {String(noOfPackages).padStart(2, "0")}
                    </span>
                  </div>
                  <hr className="my-2" />

                  <div className="preview-row">
                    <span className="preview-label">Total Weight</span>
                    <span className="preview-value">
                      {totalWeight.toFixed(2)} KG
                    </span>
                  </div>
                  <hr className="my-2" />

                  <div className="preview-row">
                    <span className="preview-label">Order Value</span>
                    <span className="preview-value">
                      {currencyName} {totalValue.toFixed(3)}
                    </span>
                  </div>
                  <hr className="my-2" />

                  <div className="preview-row">
                    <span className="preview-label">From Country</span>
                    <span className="preview-value">
                      {fromCountry?.name || "Bahrain"}
                    </span>
                  </div>
                  <hr className="my-2" />

                  <div className="preview-row">
                    <span className="preview-label">To Country</span>
                    <span className="preview-value">
                      {toCountry?.name || "-"}
                    </span>
                  </div>
                </div>
              </div>
              <div className="receipt-perforation"></div>
            </div>
          </div>

          {/* Main Content */}
          <div className="col-lg-9">
            <div className="card border-0 rounded-4 p-4 bg-light-gray shadow-sm">
              {/* From/To Section */}
              <div className="row g-0 align-items-center position-relative mb-4">
                {/* From Section */}
                <div className="col-md-5 pe-4">
                  <h6 className="font-14 font-700 mb-4 text-dark">From</h6>
                  <div className="row g-3">
                    <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-20"></i>
                          <SelectOptions
                            name="fromCountry"
                            optionsData={countries}
                            value={fromCountry}
                            onChange={(val: any) => {
                              if (val?.value !== fromCountry?.value) {
                                setFromCity(null);
                              }
                              setFromCountry(val);
                              if (errors.fromCountry) {
                                setErrors({
                                  ...errors,
                                  fromCountry: undefined,
                                });
                              }
                            }}
                            isDisabled
                            placeholder="Select Country"
                            divClassName="mb-0"
                            style={{
                              control: (base: any) => ({
                                ...base,
                                borderRadius: "15px",
                                height: "50px",
                                paddingLeft: "40px",
                                border: errors.fromCountry
                                  ? "1px solid #dc3545"
                                  : "1px solid #dee2e6",
                                boxShadow: "none",
                                "&:hover": {
                                  borderColor: errors.fromCountry
                                    ? "#dc3545"
                                    : "#dee2e6",
                                },
                              }),
                            }}
                          />
                        </div>
                        {errors.fromCountry && (
                          <div className="error-message">
                            {errors.fromCountry}
                          </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-road-map-fill text-dark-blue font-20"></i>
                          <SelectOptions
                            name="fromCity"
                            apiUrl={
                              fromCountry
                                ? `/customer/international/cities/list?country_id=${fromCountry.value}`
                                : ""
                            }
                            value={fromCity}
                            isDisabled={!fromCountry}
                            onChange={(val: any) => {
                              setFromCity(val);
                              if (errors.fromCity) {
                                setErrors({ ...errors, fromCity: undefined });
                              }
                            }}
                            placeholder={
                              !fromCountry
                                ? "Select Country First"
                                : "Select City"
                            }
                            divClassName="mb-0"
                            style={{
                              control: (base: any) => ({
                                ...base,
                                borderRadius: "15px",
                                height: "50px",
                                paddingLeft: "40px",
                                border: errors.fromCity
                                  ? "1px solid #dc3545"
                                  : "1px solid #dee2e6",
                                boxShadow: "none",
                                "&:hover": {
                                  borderColor: errors.fromCity
                                    ? "#dc3545"
                                    : "#dee2e6",
                                },
                              }),
                            }}
                          />
                        </div>
                        {errors.fromCity && (
                          <div className="error-message">{errors.fromCity}</div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                {/* Vertical Separator & Swap Button */}
                <div
                  className="col-md-2 d-flex justify-content-center align-items-center position-relative"
                  style={{ height: "100px" }}
                >
                  <div className="vertical-line"></div>
                  <button
                    className="btn btn-dark-blue rounded-3 swap-btn shadow-sm position-absolute"
                    onClick={handleSwap}
                    type="button"
                  >
                    <i className="ri-arrow-left-right-line font-18"></i>
                  </button>
                </div>

                {/* To Section */}
                <div className="col-md-5 ps-4">
                  <h6 className="font-14 font-700 mb-4 text-dark">To</h6>
                  <div className="row g-3">
                    <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-20"></i>
                          <SelectOptions
                            name="toCountry"
                            optionsData={countries}
                            value={toCountry}
                            onChange={(val: any) => {
                              if (val?.value !== toCountry?.value) {
                                setToCity(null);
                              }
                              setToCountry(val);
                              if (errors.toCountry) {
                                setErrors({ ...errors, toCountry: undefined });
                              }
                            }}
                            placeholder="Select Country"
                            divClassName="mb-0"
                            style={{
                              control: (base: any) => ({
                                ...base,
                                borderRadius: "15px",
                                height: "50px",
                                paddingLeft: "40px",
                                border: errors.toCountry
                                  ? "1px solid #dc3545"
                                  : "1px solid #dee2e6",
                                boxShadow: "none",
                                "&:hover": {
                                  borderColor: errors.toCountry
                                    ? "#dc3545"
                                    : "#dee2e6",
                                },
                              }),
                            }}
                          />
                        </div>
                        {errors.toCountry && (
                          <div className="error-message">
                            {errors.toCountry}
                          </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-road-map-fill text-dark-blue font-20"></i>
                          <SelectOptions
                            name="toCity"
                            apiUrl={
                              toCountry
                                ? `/customer/international/cities/list?country_id=${toCountry.value}`
                                : ""
                            }
                            value={toCity}
                            onChange={(val: any) => {
                              setToCity(val);
                              if (errors.toCity) {
                                setErrors({ ...errors, toCity: undefined });
                              }
                            }}
                            isDisabled={!toCountry}
                            placeholder={
                              !toCountry
                                ? "Select Country First"
                                : "Select City"
                            }
                            divClassName="mb-0"
                            style={{
                              control: (base: any) => ({
                                ...base,
                                borderRadius: "15px",
                                height: "50px",
                                paddingLeft: "40px",
                                border: errors.toCity
                                  ? "1px solid #dc3545"
                                  : "1px solid #dee2e6",
                                boxShadow: "none",
                                "&:hover": {
                                  borderColor: errors.toCity
                                    ? "#dc3545"
                                    : "#dee2e6",
                                },
                              }),
                            }}
                          />
                        </div>
                        {errors.toCity && (
                          <div className="error-message">{errors.toCity}</div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Shipment Content & Package Info */}
              <div className="row mt-4 g-3 align-items-end">
                {/* Shipment Content */}
                <div className="col-lg-4 col-md-12">
                  <h6 className="font-13 font-700 mb-3 text-dark">
                    What is Your Shipment Content?
                  </h6>

                  <div className="d-flex gap-2">
                    <button
                      type="button"
                      className={`btn btn-content-toggle ${
                        shipmentContent === "Document" ? "active" : ""
                      }`}
                      onClick={() => setShipmentContent("Document")}
                    >
                      <i className="ri-file-text-fill me-2"></i>
                      Document
                    </button>

                    <button
                      type="button"
                      className={`btn btn-content-toggle ${
                        shipmentContent === "Parcel" ? "active" : ""
                      }`}
                      onClick={() => setShipmentContent("Parcel")}
                    >
                      <i className="ri-box-3-fill me-2"></i>
                      Parcel
                    </button>
                  </div>
                </div>

                {/* Number of Packages */}
                <div className="col-lg-2 col-md-6">
                  <h6 className="font-13 font-700 mb-3 text-dark">
                    Number of Packages
                  </h6>
                  <div className="input-with-icon">
                    <i className="ri-grid-fill text-dark-blue"></i>
                    <input
                      type="number"
                      className="form-control custom-input-pill"
                      value={noOfPackages}
                      min={1}
                      onChange={(e) =>
                        handlePackagesChange(parseInt(e.target.value))
                      }
                    />
                  </div>
                </div>

                <div className="col-2">
                  <h6 className="font-13 font-700 mb-3 text-dark">
                    Default Pkg Weight
                  </h6>
                  <div className="input-with-icon">
                    <i className="ri-weight-line text-dark-blue"></i>
                    <input
                      type="number"
                      className="form-control custom-input-pill"
                      value={defaultPackageWeight}
                      onChange={(e) =>
                        handleDefaultWeightChange(e.target.value)
                      }
                      placeholder="Weight"
                    />
                  </div>
                </div>

                {/* <div className="col-md-2">
                  <h6 className="font-13 font-700 mb-3 text-dark">
                    Default Pkg Value
                  </h6>
                  <div className="input-with-icon">
                    <i className="ri-money-dollar-circle-line text-dark-blue"></i>
                    <input
                      type="number"
                      className="form-control custom-input-pill"
                      value={defaultPackageValue}
                      onChange={(e) => handleDefaultValueChange(e.target.value)}
                      placeholder="Package value"
                    />
                  </div>
                </div> */}
                <div className="col-2">
                  <h6 className="font-13 font-700 mb-3 text-dark">
                    Default Pkg description
                  </h6>
                  <div className="input-with-icon">
                    <i className="ri-money-dollar-circle-line text-dark-blue"></i>
                    <input
                      type="text"
                      className="form-control custom-input-pill"
                      value={defaultPackageDescription}
                      onChange={(e) =>
                        handleDefaultDescriptionChange(e.target.value)
                      }
                      placeholder="Package description"
                    />
                  </div>
                </div>

                <div className="col-2">
                  <h6 className="font-13 font-700 mb-3 text-dark">
                    Total Weight
                  </h6>
                  <div className="total-weight-pill d-flex align-items-center justify-content-center">
                    <i className="ri-weight-fill me-2 font-18"></i>
                    <span className="font-14 font-700">
                      {totalWeight.toFixed(2)} Kg
                    </span>
                  </div>
                </div>
              </div>

              {/* Package Grid */}
              <div className="mt-5">
                <h6 className="font-14 font-700 mb-3 text-dark">
                  No. of Packages ({String(noOfPackages).padStart(2, "0")})
                </h6>
                <PackageGrid
                  packages={packageDetails}
                  onChange={(updatedPackages) => {
                    setPackageDetails(updatedPackages);
                    if (errors.packageDetails) {
                      setErrors({ ...errors, packageDetails: undefined });
                    }
                  }}
                  errors={errors.packageDetails || null}
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <CreateOrderFooter
        step={step}
        setStep={async (nextStep) => {
          if (await validateStep1()) setStep(nextStep);
        }}
        validation={validateStep1}
        backButton={false}
        defaultOrderDetails={defaultOrderDetails}
        isEditMode={isEditMode}
        isInternational={true}
      />

      <style jsx>{`
        .bg-light-gray {
          background-color: #f8f9fa !important;
        }

        /* Receipt Sidebar Styles */
        .receipt-sidebar {
          background: white;
          border-radius: 12px 12px 0 0;
          overflow: hidden;
        }

        .receipt-content {
          background: white;
          min-height: 400px;
          padding: 1.5rem;
        }

        .receipt-perforation {
          position: relative;
          height: 1rem;
          background-color: white;
        }

        .receipt-perforation::before {
          background-image:
            linear-gradient(135deg, #f8f9fa 0.5rem, transparent 0),
            linear-gradient(-135deg, #f8f9fa 0.5rem, transparent 0);
          background-position: left-bottom;
          background-repeat: repeat-x;
          background-size: 1rem 1rem;
          content: "";
          display: block;
          position: absolute;
          top: -1rem;
          left: 0;
          width: 100%;
          height: 1rem;
          box-shadow: 0 -0.4rem 1rem -0.4rem rgba(0, 0, 0, 0.2);
          transform: rotate(180deg);
        }

        .preview-details {
          font-size: 12px;
        }

        .preview-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 4px 0;
        }

        .preview-label {
          color: #6c757d;
          font-size: 11px;
          font-weight: 500;
        }

        .preview-value {
          color: #7b3f9b;
          font-size: 12px;
          font-weight: 700;
          text-align: right;
        }

        /* Floating Label Styles */
        .floating-label-group {
          position: relative;
          margin-top: 5px;
        }

        .floating-label {
          position: absolute;
          top: -10px;
          left: 15px;
          background: #f8f9fa;
          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 Icon Styles */
        .input-with-icon {
          position: relative;
        }

        .input-with-icon i {
          position: absolute;
          left: 15px;
          top: 50%;
          transform: translateY(-50%);
          z-index: 5;
          color: #2c3e50;
        }

        .input-with-icon :global(.custom-select-rounded .css-13cymwt-control),
        .input-with-icon :global(.custom-select-rounded .css-t3ipsp-control) {
          padding-left: 45px !important;
          border-radius: 15px !important;
          border: 1px solid #dee2e6 !important;
          height: 50px !important;
        }

        /* Color Utilities */
        .text-dark-blue {
          color: #000080 !important;
        }

        .text-purple {
          color: #7b3f9b !important;
        }

        .btn-dark-blue {
          background-color: #000080;
          color: white;
          border: none;
        }

        .btn-dark-blue:hover {
          background-color: #000066;
          color: white;
        }

        /* Vertical Line & Swap Button */
        .vertical-line {
          width: 1px;
          background-color: #001a72;
          height: 100px;
          position: absolute;
        }

        .swap-btn {
          width: 40px;
          height: 40px;
          padding: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 2;
          background-color: #001a72 !important;
        }

        /* Content Toggle Buttons */
        .btn-content-toggle {
          border: 1px solid #dee2e6;
          background: white;
          border-radius: 50px;
          padding: 12px 25px;
          font-size: 13px;
          font-weight: 600;
          color: #6c757d;
          flex: 1;
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
          transition: all 0.3s ease;
        }

        .btn-content-toggle.active {
          background-color: #7b3f9b !important;
          color: white !important;
          border-color: #7b3f9b !important;
          box-shadow: 0 4px 15px rgba(123, 63, 155, 0.3);
        }

        .btn-content-toggle i {
          color: inherit;
        }

        /* Input Pill Styles */
        .custom-input-pill {
          padding-left: 45px !important;
          border-radius: 50px !important;
          height: 50px !important;
          border: 1px solid #dee2e6 !important;
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
          background-color: white !important;
        }

        .total-weight-pill {
          background-color: #7b3f9b;
          color: white;
          padding: 12px 25px;
          border-radius: 50px;
          height: 50px;
          box-shadow: 0 4px 15px rgba(123, 63, 155, 0.3);
        }

        /* Font Utilities */
        .font-10 {
          font-size: 10px;
        }
        .font-11 {
          font-size: 11px;
        }
        .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-20 {
          font-size: 20px;
        }
        .font-500 {
          font-weight: 500;
        }
        .font-600 {
          font-weight: 600;
        }
        .font-700 {
          font-weight: 700;
        }

        /* Error Message */
        .error-message {
          color: #dc3545;
          font-size: 12px;
          margin-top: 5px;
          font-weight: 500;
        }
      `}</style>
    </>
  );
};

export default Step1;
