/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { JSX, useEffect } from "react";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { MAX_WEIGHT_TOAST_MESSAGE } from "../../../../utlits/Messages";
import { useSearchParams } from "next/navigation";

interface PackageDetail {
  package_id: number;
  weight: string;
  package_description: string;
  customer_input_package_value: string;
  external_package_id?: string;
}

interface PackageFormProps {
  noOfPackages: number;
  onPackagesChange: (value: any) => void;
  packageDetails: PackageDetail[];
  onPackageDetailsChange: (updatedPackages: PackageDetail[]) => void;
  errors?: {
    packageCount?: string;
    noOfPackages?: string;
    packageDetails?: { [key: number]: any }; // keyed by index
  };
  isEditMode?: boolean;
}

const PackageForm: React.FC<PackageFormProps> = ({
  noOfPackages,
  onPackagesChange,
  packageDetails,
  onPackageDetailsChange,
  errors = {},
  // isEditMode = false
}) => {
  const searchParams: any = useSearchParams();
  const packageDisable: string = searchParams.get("packageDisable");
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  const [defaultDescription, setDefaultDescription] = React.useState(
    packageDetails[0]?.package_description || allData?.packageDescription || ""
  );
  const [defaultWeight, setDefaultWeight] = React.useState(
    packageDetails[0]?.weight || 1
  );
  // const weightOptions = [
  //   { id: 4, name: "< 5kg" },
  //   { id: 29, name: "5kg - 30kg" },
  //   // { id: 31, name: "> 30kg" },
  // ];
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [selectedWeightId, setSelectedWeightId] = React.useState<string>("");

  // Initialize selected weight from package details
  useEffect(() => {
    if (packageDetails?.[0]?.weight) {
      setSelectedWeightId(packageDetails[0].weight);
      setDefaultWeight(packageDetails[0].weight || 1);
    }
  }, [packageDetails]);

  // Initialize package details when component mounts or when noOfPackages changes
  useEffect(() => {
    // If no packages, or the number of packages doesn't match, or the first package is empty, initialize
    if (
      packageDetails.length === 0 ||
      packageDetails.length !== noOfPackages ||
      (noOfPackages === 1 &&
        (!packageDetails[0] ||
          Object.values(packageDetails[0]).every((v) => v === "" || v === 0)))
    ) {
      const updatedDetails = Array(noOfPackages)
        .fill(null)
        .map((_, index) => {
          if (packageDetails[index]) {
            return {
              package_id: packageDetails[index].package_id,
              weight: packageDetails[index].weight || 1,
              package_description: packageDetails[index].package_description,
              customer_input_package_value:
                packageDetails[index].customer_input_package_value,
              external_package_id:
                packageDetails[index].external_package_id || "",
            };
          }
          // Default package
          return {
            package_id: 1,
            weight: 1,
            package_description: defaultDescription || "",
            customer_input_package_value: "0.000",
            external_package_id: "",
          };
        }) as PackageDetail[];
      onPackageDetailsChange(updatedDetails);
    }
  }, [
    noOfPackages,
    packageDetails,
    onPackageDetailsChange,
    defaultDescription,
  ]);

  const handleWeightChange = (index: number, value: string) => {
    const numValue = Number(value);
    // Calculate the new total weight if this change is applied
    const currentTotal = packageDetails.reduce(
      (sum, pkg, i) => sum + (i === index ? 0 : Number(pkg.weight) || 0),
      0
    );
    const newTotal = currentTotal + (Number(value) || 0);
    if (newTotal > 30) {
      toast.warning(MAX_WEIGHT_TOAST_MESSAGE, {
        position: "top-right",
        autoClose: 3000,
      });
      return;
    }
    if (numValue < 1 && value !== "") {
      // Optionally set an error here, or handle via validation
      // For now, just prevent update
      return;
    }
    const updated = [...packageDetails];
    updated[index] = {
      ...updated[index],
      weight: value,
      // Ensure defaults if missing
      package_id: updated[index]?.package_id ?? 1,
      package_description:
        updated[index]?.package_description ?? (defaultDescription || ""),
      customer_input_package_value:
        updated[index]?.customer_input_package_value ?? "0.000",
      external_package_id: updated[index]?.external_package_id ?? "",
    };
    onPackageDetailsChange(updated);
  };

  const handleDescriptionChange = (index: number, value: string) => {
    const updated = [...packageDetails];
    updated[index] = { ...updated[index], package_description: value };
    onPackageDetailsChange(updated);
  };

  const handlePackageValueChange = (index: number, value: string) => {
    const updated = [...packageDetails];
    updated[index] = {
      ...updated[index],
      customer_input_package_value: value || "0.000",
    };
    onPackageDetailsChange(updated);
  };

  const handleExternalPackageIdChange = (index: number, value: string) => {
    // Limit string length if needed, e.g., 50 chars
    if (value.length > 50) return;

    const updated = [...packageDetails];
    updated[index] = {
      ...updated[index],
      external_package_id: value,
    };
    onPackageDetailsChange(updated);
  };

  const safePackageDetails =
    packageDetails.length === 0
      ? [
          {
            package_id: 1,
            weight: "",
            package_description: defaultDescription || "",
            customer_input_package_value: "0.000",
            external_package_id: "",
          },
        ]
      : packageDetails;
  const renderPackageFields = (): JSX.Element[] => {
    return safePackageDetails.map((pkg: any, index) => (
      <div key={index}>
        <div className="row mb-3 px-0 mx-0">
          {/* Weight Input */}
          <div className="col-lg-3 col-md-6 col-12 input-style input-style-always-active has-borders has-icon validate-field">
            <div className="position-relative input-icon-position">
              <i className="ri ri-weight-line color-primary" />
              <input
                type="number"
                className={`form-control ${
                  errors?.packageDetails?.[index]?.weight ? "is-invalid" : ""
                }`}
                id={`form-package-${index}`}
                value={pkg.weight === 0 ? "" : String(pkg.weight)}
                onChange={(e) => handleWeightChange(index, e.target.value)}
                placeholder="Enter package weight (KG)"
                disabled={packageDisable == "true" ? true : false}
              />
            </div>
            <label
              htmlFor={`form-package-${index}`}
              className="color-theme opacity-80 text-uppercase font-700 font-10"
            >
              Package {index + 1} Weight (KG) <b className="color-red">*</b>
            </label>
            {errors?.packageDetails?.[index]?.weight ? (
              <div className="text-danger">
                {errors?.packageDetails[index].weight}
              </div>
            ) : safePackageDetails?.length === 1 &&
              errors?.packageDetails &&
              typeof errors?.packageDetails === "string" ? (
              <div className="text-danger">{"Weight is required."}</div>
            ) : (
              ""
            )}
          </div>

          {/* Description Input */}
          <div className="col-lg-3 col-md-6 col-12 input-style input-style-always-active has-borders has-icon validate-field">
            <div className="position-relative input-icon-position">
              <i className="ri ri-draft-line color-primary" />
              <input
                type="text"
                className={`form-control ${
                  errors?.packageDetails?.[index]?.package_description
                    ? "is-invalid"
                    : ""
                }`}
                id={`description-package-${index}`}
                value={pkg?.package_description ? pkg?.package_description : ""}
                onChange={(e) => handleDescriptionChange(index, e.target.value)}
                placeholder="Enter package description"
                disabled={packageDisable == "true" ? true : false}
              />
            </div>
            <label
              htmlFor={`description-package-${index}`}
              className="color-theme opacity-80 text-uppercase font-700 font-10"
            >
              Package {index + 1} Description
            </label>
            {errors?.packageDetails?.[index]?.package_description && (
              <div className="text-danger">
                {errors?.packageDetails[index].package_description}
              </div>
            )}
          </div>

          {/* Package Value */}
          <div className="col-lg-3 col-md-6 col-12 input-style input-style-always-active has-borders has-icon validate-field">
            <div className="position-relative input-icon-position">
              <i className="ri ri-cash-line color-primary" />
              <input
                type="number"
                className={`form-control ${
                  errors?.packageDetails?.[index]?.customer_input_package_value
                    ? "is-invalid"
                    : ""
                }`}
                id={`value-package-${index}`}
                value={
                  pkg.customer_input_package_value == 0
                    ? ""
                    : pkg.customer_input_package_value
                }
                onChange={(e) =>
                  handlePackageValueChange(index, e.target.value)
                }
                placeholder="Enter the package value"
                disabled={packageDisable == "true" ? true : false}
              />
            </div>
            <label
              htmlFor={`value-package-${index}`}
              className="color-theme opacity-80 text-uppercase font-700 font-10"
            >
              Package {index + 1} Value
            </label>
            {errors?.packageDetails?.[index]?.customer_input_package_value && (
              <div className="text-danger">
                {errors?.packageDetails[index].customer_input_package_value}
              </div>
            )}
          </div>

          {/* External Package ID */}
          <div className="col-lg-3 col-md-6 col-12 input-style input-style-always-active has-borders has-icon validate-field">
            <div className="position-relative input-icon-position">
              <i className="ri ri-barcode-box-line color-primary" />
              <input
                type="text"
                className="form-control"
                id={`external-id-package-${index}`}
                value={pkg.external_package_id || ""}
                onChange={(e) =>
                  handleExternalPackageIdChange(index, e.target.value)
                }
                placeholder="External Package ID"
                disabled={packageDisable == "true" ? true : false}
              />
            </div>
            <label
              htmlFor={`external-id-package-${index}`}
              className="color-theme opacity-80 text-uppercase font-700 font-10"
            >
              Ext. Package ID
            </label>
            {errors?.packageDetails?.[index]?.external_package_id && (
              <div className="text-danger">
                {errors?.packageDetails[index].external_package_id}
              </div>
            )}
          </div>
        </div>
      </div>
    ));
  };

  // const handleWeightSelection = (packageWeight: {
  //   id: number;
  //   name: string;
  // }) => {
  //   setSelectedWeightId(String(packageWeight.id));
  //   setDefaultWeight(String(packageWeight.id));
  //   const updated = [...packageDetails];
  //   if (updated.length === 0) {
  //     updated.push({
  //       package_id: 1,
  //       weight: String(packageWeight.id),
  //       package_description: defaultDescription || "",
  //       customer_input_package_value: "0.000",
  //     });
  //   } else {
  //     // Update all packages with the same weight
  //     const updated = packageDetails.map((pkg) => ({
  //       ...pkg,
  //       weight: String(packageWeight.id),
  //     }));
  //     onPackageDetailsChange(updated);
  //   }
  // };

  return (
    <>
      <style>
        {`
        .add-sub-package-fields {
          border: 1px solid #e6e4e4;
         border-radius: 8px;
         padding-top: 15px;
        }
        @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
          .sendPackageBox .add-sub-package-fields .input-style {
              margin-bottom: 5px !important;
          }
        }
          .no-drop-readonly {
            background-color: #eee;
            cursor: no-drop;
            opacity: 0.5;
          }          
          .no-drop-border-round {
            border-radius: 17px !important;
          }
          .no-drop-readonly input {
            background-color: #eee;
            cursor: no-drop;
            // opacity: 0.5;
          }
        `}
      </style>
      <div className="col-lg-2">
        <div className="input-style input-style-always-active has-borders has-icon validate-field mt-0 international-form-input">
          <h5 className="font-15 pb-1">
            No.of packages <b className="color-red">*</b>
          </h5>
          <div
            className={`position-relative input-icon-position ${
              packageDisable === "true"
                ? "no-drop-readonly no-drop-border-round"
                : ""
            }`}
          >
            <i className="ri ri-archive-line color-primary" />
            <input
              type="number"
              className={`form-control ${
                errors?.packageCount ? "is-invalid" : ""
              }`}
              id="form1ab"
              placeholder="No. of packages"
              disabled={packageDisable == "true" ? true : false}
              value={noOfPackages === 0 ? "" : noOfPackages}
              // min={1}
              onChange={(e) => onPackagesChange(Number(e.target.value))}
            />
          </div>
          {/* <label
              htmlFor="form1ab"
              className="color-theme opacity-80 text-uppercase font-700 font-10"
            >
              No.of packages <b className="color-red">*</b>
            </label> */}
          {errors?.packageCount && (
            <div className="text-danger">{errors?.packageCount}</div>
          )}
        </div>
      </div>
      <div className="col-lg-12">
        {/* Number of Packages */}
        <div className="d-lg-flex gap-2">
          {noOfPackages > 1 && (
            <>
              <div className="input-style input-style-always-active has-borders has-icon validate-field mt-2 col-lg-4">
                <div
                  className={`position-relative input-icon-position  ${
                    packageDisable === "true" ? "no-drop-readonly" : ""
                  }`}
                >
                  <i className="ri ri-draft-line color-primary" />
                  <input
                    type="text"
                    className="form-control"
                    placeholder="Enter package description"
                    value={defaultDescription}
                    onChange={(e) => {
                      setDefaultDescription(e.target.value);
                      // Update all packages with the same description
                      const updated = packageDetails.map((pkg) => ({
                        ...pkg,
                        package_description: e.target.value,
                      }));
                      onPackageDetailsChange(updated);
                    }}
                    disabled={packageDisable == "true" ? true : false}
                  />
                </div>
                <label className="color-theme opacity-80 text-uppercase font-700 font-10">
                  Default Package Description
                </label>
              </div>
              <div className="input-style input-style-always-active has-borders has-icon validate-field mt-2 col-lg-4">
                <div
                  className={`position-relative input-icon-position ${
                    packageDisable === "true" ? "no-drop-readonly" : ""
                  }`}
                >
                  <i className="ri ri-weight-line color-primary" />
                  <input
                    type="number"
                    className="form-control"
                    placeholder="Enter package weight"
                    value={defaultWeight}
                    onChange={(e) => {
                      const value = e?.target?.value;
                      const numValue = Number(value);
                      // Calculate the new total weight if this change is applied to all packages
                      const newTotal =
                        numValue === 0 ? 0 : numValue * packageDetails.length;
                      if (newTotal > 30) {
                        toast.warning(MAX_WEIGHT_TOAST_MESSAGE, {
                          position: "top-right",
                          autoClose: 3000,
                        });
                        return;
                      }
                      // if (numValue < 1 && value !== "") {
                      //   // Optionally set an error here, or handle via validation
                      //   // For now, just prevent update
                      //   return;
                      // }
                      setDefaultWeight(e.target.value);
                      // Update all packages with the same weight
                      const updated = packageDetails.map((pkg) => ({
                        ...pkg,
                        weight: e.target.value,
                      }));
                      onPackageDetailsChange(updated);
                    }}
                    disabled={packageDisable == "true" ? true : false}
                  />
                </div>
                <label className="color-theme opacity-80 text-uppercase font-700 font-10">
                  Default Package Weight
                </label>
              </div>
            </>
          )}
        </div>

        {/* Single or Multiple Package Inputs */}
        {/* {noOfPackages === 1 ? (
          <>
            <div className="row align-items-center mb-0">
              <div className="col-lg-12 col-md-6 col-sm-12 mb-3">
                <h5 className="font-15 pb-1">Package Weight</h5>
                <div className="px-2 pe-0">
                  {weightOptions.map((option) => {
                    let iconClass = "";
                    if (option.name === "< 5kg") iconClass = "ri-instance-line";
                    else if (option.name === "5kg - 30kg")
                      iconClass = "ri-stacked-view";
                    else if (option.name === "> 30kg")
                      iconClass = "ri-weight-line";

                    return (
                      <div
                        className="form-check interest-check"
                        key={option.id}
                      >
                        <input
                          className="form-check-input"
                          type="radio"
                          id={`check${option.id}`}
                          name="weightGroup"
                          checked={
                            String(selectedWeightId) === String(option.id)
                          }
                          onChange={() => handleWeightSelection(option)}
                        />
                        <label
                          className="form-check-label shadow-xl rounded-xl"
                          htmlFor={`check${option.id}`}
                        >
                          {option.name}
                        </label>
                        <i className="fa fa-check-circle color-white font-18" />
                        <i className={`${iconClass} font-17 color-yellow2`} />
                      </div>
                    );
                  })}
                  {errors?.packageDetails?.[0]?.weight && (
                    <div className="text-danger mb-1">
                      {errors?.packageDetails[0]?.weight}
                    </div>
                  )}
                </div>
              </div>
            </div>

            <div className="row align-items-center">
              <div className="col-md-6 input-style input-style-always-active has-borders has-icon validate-field">
                <div className="position-relative input-icon-position">
                  <i className="ri ri-draft-line color-primary" />
                  <input
                    type="text"
                    className={`form-control ${
                      errors?.packageDetails?.[0]?.package_description
                        ? "is-invalid"
                        : ""
                    }`}
                    value={packageDetails?.[0]?.package_description || ""}
                    onChange={(e) => handleDescriptionChange(0, e.target.value)}
                    placeholder="Enter package description"
                  />
                </div>
                <label className="color-theme opacity-80 text-uppercase font-700 font-10">
                  Package Description
                </label>
                {errors?.packageDetails?.[0]?.package_description && (
                  <div className="text-danger">
                    {errors?.packageDetails[0]?.package_description}
                  </div>
                )}
              </div>

              <div className="col-md-6 input-style input-style-always-active has-borders has-icon validate-field">
                <div className="position-relative input-icon-position">
                  <i className="ri ri-cash-line color-primary" />
                  <input
                    type="text"
                    className={`form-control ${
                      errors?.packageDetails?.[0]?.customer_input_package_value
                        ? "is-invalid"
                        : ""
                    }`}
                    value={
                      packageDetails[0]?.customer_input_package_value || ""
                    }
                    onChange={(e) =>
                      handlePackageValueChange(0, e.target.value)
                    }
                    placeholder="Enter the package value"
                  />
                </div>
                <label className="color-theme opacity-80 text-uppercase font-700 font-10">
                  Package Value
                </label>
                {errors?.packageDetails?.[0]?.customer_input_package_value && (
                  <div className="text-danger">
                    {errors?.packageDetails[0]?.customer_input_package_value}
                  </div>
                )}
              </div>
            </div>
          </>
        ) : ( */}
        <div
          className={`row mx-0 mb-0 add-sub-package-fields ${
            packageDisable === "true" ? "no-drop-readonly" : ""
          }`}
        >
          <h5 className="font-15 pb-2 mb-2">
            No.of Packages ({packageDetails?.length || 0})
          </h5>
          {renderPackageFields()}
        </div>
        {/* )} */}
      </div>
    </>
  );
};

export default PackageForm;
