/* eslint-disable jsx-a11y/role-has-required-aria-props */
/* eslint-disable @next/next/no-img-element */
/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import React from "react";

type PackageItem = {
  id?: number | string;
  packageId?: number | string;
  packageTypeId?: number | string;
  weight?: number | string;
  packageDescription?: string;
  customerInputPackageValue?: number | string;
};

interface Props {
  orderDetails: any;
  onConfirm: (selectedPackages: PackageItem[]) => void;
  onCancel: () => void;
}

const CreateReturnOrderModal: React.FC<Props> = ({ orderDetails, onConfirm, onCancel }) => {
  const packages: PackageItem[] = React.useMemo(() => {
    const list = orderDetails?.order_package_list || orderDetails?.draft_order_package_list || [];
    return Array.isArray(list) ? list : [];
  }, [orderDetails]);

  const [selectedIds, setSelectedIds] = React.useState<Set<string | number>>(new Set());

  React.useEffect(() => {
    if (packages.length > 0) {
      const allKeys = packages.map((p, idx) => (p.id ?? p.packageId ?? p.packageTypeId ?? idx));
      setSelectedIds(new Set(allKeys as any));
    } else {
      setSelectedIds(new Set());
    }
  }, [packages]);

  const toggle = (pkgId: string | number) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(pkgId)) next.delete(pkgId); else next.add(pkgId);
      return next;
    });
  };

  const allSelected = packages.length > 0 && selectedIds.size === packages.length;
  const toggleAll = () => {
    if (allSelected) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(packages.map((p, idx) => (p.id ?? p.packageId ?? p.packageTypeId ?? idx))));
    }
  };

  const handleConfirm = () => {
    const selected = packages.filter((p, idx) => {
      const key = p.id ?? p.packageId ?? p.packageTypeId ?? idx;
      return selectedIds.has(key as any);
    }).map((p) => ({
      id: p.id,
      packageId: p.packageId ?? p.packageTypeId,
      packageTypeId: p.packageTypeId ?? p.packageId,
      weight: p.weight,
      packageDescription: p.packageDescription,
      customerInputPackageValue: p.customerInputPackageValue,
    }));
    onConfirm(selected);
  };

  return (
    <>
      <style>
        {`
                                  .package-return-box input:hover, .package-return-box input[type="checkbox"] {
                                    // border: 1px solid #333 !important;
                                    accent-color: #6c9f6a !important;
                                  }
                                    .bg-highlight input[type="checkbox"] {
                                    // border: 1px solid #fff !important;
                                      accent-color: #6c9f6a !important;  
                                    }
                                      .bg-highlight .order-icons {
                                        filter: drop-shadow(0px 1000px 0 white);
                                        transform: translateY(-1000px);
                                      }
                                  
                                `}
      </style>
      <div
        id="order-filter"
        className="menu menu-box-bottom rounded-m order-filter bg-white col-lg-5 menu-active text-dark"
        style={{ display: "block" }}
      >
        <div className="menu-title">
          <h1 className="font-24">Select Packages for Return</h1>
          <a href="#" className="close-menu" onClick={onCancel}>
            <i className="fa fa-times-circle" />
          </a>
        </div>
        <div className="signin-box filter-section">
          <div className="row mx-0 px-2">
            {packages.length === 0 ? (
              <div className="col-lg-6">
                <div className="card card-style m-lg-0">
                  <div className="content filter-content-box" id="tab-group-3">
                    <div className="content filter-content draft mx-0 bg-transparent px-0 collapse show">
                      <div style={{ maxHeight: "50vh", overflowY: "auto" }}>
                        <div className="text-center py-4">No packages found for this order.</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              packages.map((pkg, idx) => {
                const key = pkg.id ?? pkg.packageId ?? pkg.packageTypeId ?? idx;
                const checked = selectedIds.has(key as any);
                return (
                  <>
                    <div className="col-lg-6">
                      <div className="card card-style m-lg-0">
                        <div className="content filter-content-box" id="tab-group-3">
                          <div className="content filter-content draft mx-0 bg-transparent px-0 collapse show">
                            <div style={{ maxHeight: "50vh", overflowY: "auto" }}>
                              <label key={String(key)} className={`card card-style package-retun-label p-3 mb-0 mx-0 d-block ${checked ? "bg-highlight1" : ""}`} style={{ cursor: "pointer" }}>
                                <div className="d-flex align-items-start package-return-box gap-2">
                                  <span
                                    className="form-control-checkbox"
                                    role="checkbox"
                                    area-checked={checked}
                                    tabIndex={0}
                                    onClick={() => toggle(key as any)}
                                    onKeyDown={(e) => {
                                      if (e.key === " " || e.key === "Enter") {
                                        e.preventDefault();
                                        toggle(key as any);
                                      }
                                    }}
                                    // style={{ width: 18, height: 18 }}
                                    style={{
                                      display: "inline-flex",
                                      alignItems: "center",
                                      justifyContent: "center",
                                      width: 18,
                                      height: 18,
                                      minWidth: 20,
                                      minHeight: 20,
                                      borderRadius: 4,
                                      border: checked ? "2px solid #16a34a" : "2px solid #cbd5e1",
                                      backgroundColor: checked ? "#eafff1" : "#ffffff",
                                      color: checked ? "#16a34a" : "#94a3b8",
                                      cursor: "pointer",
                                      transition: "all 0.15s ease-in-out",
                                    }}
                                  >
                                    <i className={`fa ${checked ? "fa-check" : ""}`} style={{ fontSize: 12 }} />
                                  </span>
                                  <div className="flex-grow-1">
                                    <div className="d-float-center justify-content-between">
                                      <strong className="font-13">Package {idx + 1}</strong>
                                      <div className="d-float-center weight">
                                        <img alt="Weight Icon" loading="lazy" width="16" height="16" decoding="async" data-nimg="1" className="order-icons img-fluid" src="/images/icons/weight.svg" style={{ color: "transparent" }}></img>
                                        <span className="badge01 rounded-xs font-11">{Number(pkg?.weight || 0)} KG</span>
                                      </div>
                                    </div>
                                    <div className="opacity-80 font-12 mt-1">
                                      {pkg?.packageDescription || "No description"}
                                    </div>
                                    <div className="d-float-center wallet">
                                      <img alt="Wallet Icon" loading="lazy" width={12} height={12} decoding="async" data-nimg={1} className="order-icons img-fluid" src="/images/icons/wallet.svg" style={{ color: "transparent" }} />
                                      {pkg?.customerInputPackageValue ? (
                                        <div className="opacity-80 font-12">Value: {String(pkg.customerInputPackageValue)}</div>
                                      ) : null}
                                    </div>

                                  </div>
                                </div>
                              </label>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </>
                );
              })
            )}
          </div>
          {/* <div className="col-lg-12 px-lg-2">
                <button
                  type="button"
                  // onClick={onConfirmClick}
                  // disabled={!isFormValid}
                  className="btn btn-full w-100 btn-l font-600 font-13 bg-blue-dark mt-0 mb-2 rounded-s text-uppercase"
                >
                </button>
              </div> */}
          <div className="col-lg-12 px-lg-2">
            <div className="row g-2">
              <div className="col-6">
                <button className="btn btn-full w-100 btn-l font-600 font-13 delybell-dark mt-0 mb-2 rounded-s text-uppercase" onClick={toggleAll}>
                  {allSelected ? "Unselect All" : "Select All"}
                </button>
              </div>
              <div className="col-6">
                <button
                  type="button"
                  className="btn btn-full w-100 btn-l font-600 font-13 bg-blue-dark mt-0 mb-2 rounded-s text-uppercase"
                  onClick={handleConfirm}
                  disabled={selectedIds.size === 0}
                >
                  Continue
                </button>
              </div>
            </div>
          </div>

        </div>
      </div>
      {/* <div className="p-2">
      <div className="d-float-center justify-content-between mb-2">
        <h5 className="font-15 pb-1 mb-0">Select Packages for Return</h5>
        <button className="btn btn-sm btn-outline-primary" onClick={toggleAll}>
          {allSelected ? "Unselect All" : "Select All"}
        </button>
      </div>
      <div style={{ maxHeight: "50vh", overflowY: "auto" }}>
        {packages.length === 0 ? (
          <div className="text-center py-4">No packages found for this order.</div>
        ) : (
          packages.map((pkg, idx) => {
            const key = pkg.id ?? pkg.packageId ?? pkg.packageTypeId ?? idx;
            const checked = selectedIds.has(key as any);
            return (
              <label key={String(key)} className={`card card-style p-2 mb-2 d-block ${checked ? "bg-highlight" : ""}`} style={{ cursor: "pointer" }}>
                <div className="d-flex align-items-center gap-2">
                  <input
                    type="checkbox"
                    checked={checked}
                    onChange={() => toggle(key as any)}
                    style={{ width: 18, height: 18 }}
                  />
                  <div className="flex-grow-1">
                    <div className="d-float-center justify-content-between">
                      <strong className="font-13">Package {idx + 1}</strong>
                      <span className="badge rounded-xs font-11">{Number(pkg?.weight || 0)} KG</span>
                    </div>
                    <div className="opacity-80 font-12 mt-1">
                      {pkg?.packageDescription || "No description"}
                    </div>
                    {pkg?.customerInputPackageValue ? (
                      <div className="opacity-80 font-12">Value: {String(pkg.customerInputPackageValue)}</div>
                    ) : null}
                  </div>
                </div>
              </label>
            );
          })
        )}
      </div>

      <div className="d-flex gap-2 mt-3">
        <button className="btn btn-full btn-l font-600 font-13 rounded-s delybell-dark" onClick={onCancel}>
          Cancel
        </button>
        <button
          className="btn btn-full btn-l font-600 font-13 rounded-s delybell-primary"
          onClick={handleConfirm}
          disabled={selectedIds.size === 0}
        >
          Continue
        </button>
      </div>
    </div> */}
    </>
  );
};

export default CreateReturnOrderModal;


