/* 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 HourGlassLoader from "../../../Loader/Loader";
import { initiateInternationalDraftOrder } from "../../../../Api/InternationalOrderApi";

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

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 [isLoading, setIsLoading] = useState<boolean>(false);
  const createOrderData: any = useAppSelector(
    (state) => state.createOrder
  )?.step1;

  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 [fromCityLoading, setFromCityLoading] = useState(false);
  const [toCityLoading, setToCityLoading] = useState(false);

  const [shipmentContent, setShipmentContent] = useState<"Document" | "Parcel">(
    "Parcel"
  );
  const [noOfPackages, setNoOfPackages] = useState<number>(1);
  const [packageDetails, setPackageDetails] = useState<PackageDetail[]>([
    {
      weight: "",
      length: "",
      width: "",
      height: "",
      package_description: "",
      customer_input_package_value: "",
    },
  ]);

  const [countries, setCountries] = useState<OptionType[]>([]);
  const [fromCities, setFromCities] = useState<OptionType[]>([]);
  const [toCities, setToCities] = useState<OptionType[]>([]);

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

  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);
        }
      } catch (err) {
        console.error("Error fetching countries:", err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchCountries();
  }, []);

useEffect(() => {
  if (!fromCountry) return;

  setFromCity(null); // reset ONLY when fromCountry changes
  setFromCities([]);

  const fetchFromCities = async () => {
    try {
      setFromCityLoading(true);
      const response = await getInternationalCities({
        country_id: fromCountry.value,
      });

      if (response?.status) {
        setFromCities(
          response.data.map((c: any) => ({
            value: c.id,
            label: c.name,
            name: c.name,
            id: c.id,
          }))
        );
      }
    } catch (err) {
      console.error("Error fetching from cities:", err);
    } finally {
      setFromCityLoading(false);
    }
  };

  fetchFromCities();
}, [fromCountry]);

useEffect(() => {
  if (!toCountry) return;

  setToCity(null); // reset ONLY when toCountry changes
  setToCities([]);

  const fetchToCities = async () => {
    try {
      setToCityLoading(true);
      const response = await getInternationalCities({
        country_id: toCountry.value,
      });

      if (response?.status) {
        setToCities(
          response.data.map((c: any) => ({
            value: c.id,
            label: c.name,
            name: c.name,
            id: c.id,
          }))
        );
      }
    } catch (err) {
      console.error("Error fetching to cities:", err);
    } finally {
      setToCityLoading(false);
    }
  };

  fetchToCities();
}, [toCountry]);


  useEffect(() => {
    if (createOrderData) {
      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);
      // Check both packageDetails and package_details
      if (createOrderData.packageDetails)
        setPackageDetails(createOrderData.packageDetails);
      else if (createOrderData.package_details)
        setPackageDetails(createOrderData.package_details);
    }
  }, [createOrderData]);

  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 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 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 (only length, width, height are mandatory)
    const packageErrors: { [key: number]: { [field: string]: string } } = {};
    packageDetails.forEach((pkg, index) => {
      const pkgErrors: { [field: string]: string } = {};

      // Only validate dimensions - weight, description, and value are optional
      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.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;
    }

    // Set errors and return false if any validation failed
    if (
      Object.keys(newErrors).length > 0 ||
      Object.keys(packageErrors).length > 0
    ) {
      setErrors(newErrors);
      return false;
    }

    // Clear errors if validation passed
    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);
      const response = await initiateInternationalDraftOrder(payload);
      console.log(response, "asdf");
      if (response.status) {
        onSave({ ...payload, draft_order_id: response.data.id });
        return true;
      } else {
        // Handle API error
        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);
    }
  };

  return (
    <>
      {isLoading && <HourGlassLoader />}
      <div className="scrollWrap step1-international p-4 bg-white">
        <div className="row g-4">
          {/* Main Content */}
          <div className="col-lg-12">
            <div className="card border-0 rounded-4 p-4 bg-light-gray shadow-none">
              <div className="row g-0 align-items-center position-relative">
                {/* From Section */}
                <div className="col-md-5 pe-4">
                  <h6 className="font-14 font-700 mb-4">From</h6>
                  <div className="row g-4">
                    <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) => {
                              setFromCountry(val);
                              if (errors.fromCountry) {
                                setErrors({
                                  ...errors,
                                  fromCountry: undefined,
                                });
                              }
                            }}
                            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"
                            optionsData={fromCities}
                            value={fromCity}
                            isDisabled={!fromCountry || fromCityLoading}
                            onChange={(val: any) => {
                              setFromCity(val);
                              if (errors.fromCity) {
                                setErrors({ ...errors, fromCity: undefined });
                              }
                            }}
                            placeholder={
                              !fromCountry
                                ? "Select Country First"
                                : fromCityLoading
                                ? "Loading cities..."
                                : "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"
                    style={{
                      height: "100%",
                      width: "1px",
                      backgroundColor: "#dee2e6",
                    }}
                  ></div>
                  <button
                    className="btn btn-dark-blue rounded-3 swap-btn shadow-sm position-absolute"
                    onClick={handleSwap}
                    style={{
                      width: "40px",
                      height: "40px",
                      padding: "0",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    <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">To</h6>
                  <div className="row g-4">
                    <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) => {
                              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"
                            optionsData={toCities}
                            value={toCity}
                            onChange={(val: any) => {
                              setToCity(val);
                              if (errors.toCity) {
                                setErrors({ ...errors, toCity: undefined });
                              }
                            }}
                            isDisabled={!toCountry || toCityLoading}
                            placeholder={
                              !toCountry
                                ? "Select Country First"
                                : toCityLoading
                                ? "Loading cities..."
                                : "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>

              <div className="row mt-5 g-4 align-items-end">
                <div className="col-md-5">
                  <h6 className="font-13 font-700 mb-3">
                    What is Your Shipment Content?
                  </h6>
                  <div className="d-flex gap-3">
                    <button
                      className={`btn btn-content-toggle d-flex align-items-center justify-content-center ${
                        shipmentContent === "Document" ? "active" : ""
                      }`}
                      onClick={() => setShipmentContent("Document")}
                    >
                      <i className="ri-file-text-fill me-2 text-warning font-18"></i>{" "}
                      Document
                    </button>
                    <button
                      className={`btn btn-content-toggle d-flex align-items-center justify-content-center ${
                        shipmentContent === "Parcel" ? "active" : ""
                      }`}
                      onClick={() => setShipmentContent("Parcel")}
                    >
                      <i
                        className={`me-2 font-18 ${
                          shipmentContent === "Parcel"
                            ? "ri-checkbox-circle-fill"
                            : "ri-checkbox-circle-line"
                        }`}
                      ></i>{" "}
                      Parcel
                    </button>
                  </div>
                </div>

                <div className="col-md-3">
                  <h6 className="font-13 font-700 mb-3">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}
                      onChange={(e) =>
                        handlePackagesChange(parseInt(e.target.value))
                      }
                      min="1"
                    />
                  </div>
                </div>

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

              <div className="mt-5">
                <h6 className="font-14 font-700 mb-3">
                  No. of Packages ({String(noOfPackages).padStart(2, "0")})
                </h6>
                <PackageGrid
                  packages={packageDetails}
                  onChange={(updatedPackages) => {
                    setPackageDetails(updatedPackages);
                    // Clear package errors when user updates
                    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 {
          background: white;
          border-radius: 12px 12px 0 0;
        }
        .receipt-content {
          background: white;
          border-radius: 12px 12px 0 0;
          min-height: 400px;
        }
        .receipt-perforation {
          height: 20px;
          background-image: radial-gradient(
            circle at 10px 0,
            transparent 10px,
            white 10px
          );
          background-size: 20px 20px;
          background-position: 0 0;
          background-repeat: repeat-x;
          filter: drop-shadow(0 4px 2px rgba(0, 0, 0, 0.05));
        }
        .floating-label-group {
          position: relative;
          margin-top: 5px;
        }
        .floating-label {
          position: absolute;
          top: -10px;
          left: 15px;
          background: #f8f9fa; /* Match card background */
          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: #2c3e50;
        }
        .text-dark-blue {
          color: #000080 !important;
        }
        .btn-dark-blue {
          background-color: #000080;
          color: white;
        }
        .btn-dark-blue:hover {
          background-color: #000066;
          color: white;
        }
        .vertical-line {
          height: 100%;
          width: 1px;
          background-color: #dee2e6;
        }
        .swap-btn {
          z-index: 11;
          border: none;
        }
        .input-with-icon :global(.custom-select-rounded .css-13cymwt-control),
        .input-with-icon :global(.custom-select-rounded .css-t3ipsp-control) {
          padding-left: 35px !important;
          border-radius: 10px !important;
          border: 1px solid #dee2e6 !important;
          height: 45px !important;
        }
        .custom-input-rounded {
          padding-left: 40px !important;
          border-radius: 10px !important;
          height: 45px !important;
          border: 1px solid #dee2e6 !important;
        }
        .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;
          border: none !important;
        }
        .btn-dark-blue {
          background-color: #001a72 !important;
          color: white !important;
        }
        .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);
        }
        .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-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-20 {
          font-size: 20px;
        }
        .font-600 {
          font-weight: 600;
        }
        .font-700 {
          font-weight: 700;
        }
        .error-message {
          color: #dc3545;
          font-size: 12px;
          margin-top: 5px;
          font-weight: 500;
        }
      `}</style>
    </>
  );
};

export default Step1;
