/* eslint-disable @typescript-eslint/no-explicit-any */
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import HourGlassLoader from "../../Loader/Loader";
import { updateStaffStatus } from "../../../Api/CustomerApi";
import Swal from "sweetalert2";
import NoData from "../../NoDataContainer/NoData";
import Modal from "../../Modal/Modal";
import OverView from "./Containers/OverView";
import ShipmentPreview from "./Containers/ShipmentPreview";
import { getShipmentDetails, listShipments } from "../../../Api/ShipmentApi";
import ShipmentCard from "./Containers/ShipmentCard";
import { useRouter, useSearchParams } from "next/navigation";
import ShipmentFilter from "../../Modal/Filters/ShipmentFilter";
import { ShipmentMode, ShipmentStatus, ShipmentTypeForCustomer } from "@/Constant/enums";

export default function AddUsersIndex() {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [step, setStep] = useState<number>(1);
  const dropdownRef = useRef<HTMLDivElement | null>(null);
  const [addUserModal, setAddUserModal] = useState(false);
  const [viewShipmentModal, setViewShipmentModal] = useState<boolean>(false);
  const [users, setUsers] = useState<any>([]);
  const [shipmentDetails, setShipmentDetails] = useState<any>({})
  const searchParams = useSearchParams();
  const [filterModal, setFilterModal] = useState<boolean>(false);
  const toggleFilter = () => setFilterModal(!filterModal);
  const [shipmentFilters, setShipmentFilters] = useState<any>({});
  useEffect(() => {
    const id = searchParams.get("id"); 
    const isEdit = searchParams.get("edit"); 
    if (id) {
      (async () => {
        try {
          setIsLoading(true);
          const data = await getShipmentDetails(Number(id));
          setShipmentDetails(data?.shipmentDetails);
          if (isEdit === "true") setStep(1) 
          else setStep(2); // open in "view" mode directly if you want
          setAddUserModal(true); // auto-open modal if needed
        } catch (error) {
          console.error("Failed to fetch shipment details:", error);
        } finally {
          setIsLoading(false);
        }
      })();
    }
  }, [searchParams]);
  
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [activeMenu, setActiveMenu] = useState<number | null>(null);
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setActiveMenu(null);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);
  const fetchOrders = async () => {
    setIsLoading(true);
    try {
      const staffList = await listShipments(shipmentFilters);
      setUsers(staffList);
    } catch (error) {
      console.error("Failed to fetch staffs:", error);
    } finally {
      setIsLoading(false);
    }
  };
  const toggle = () => {
    setAddUserModal(!addUserModal);
    setShipmentDetails({});
    if (addUserModal) {
      fetchOrders();
    } else {
      // router.push(`${window.location.pathname}`);
    }
  };
  const toggleShipmentView = () => setViewShipmentModal(!viewShipmentModal);
  const handleEdit = (item: any) => {
    setShipmentDetails(item);
    setStep(1)
    toggle();
    router.push(`${window.location.pathname}?id=${item?.id}&edit=true`);
  };
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleChangeStatus = async (item: any) => {
    try {
      setIsLoading(true);
      const response = await updateStaffStatus(item?.id, {
        is_active: item?.isActive ? false : true,
      });
      if (response?.status) {
        await fetchOrders();
        Swal.fire({
          icon: "success",
          title: "Status Updated",
          text: response?.message,
          customClass: {
            confirmButton: "delybell-primary px-4",
            cancelButton: "delybell-dark",
          },
        });
      } else
        Swal.fire({
          icon: "error",
          title: "Error",
          text: response?.message,
          customClass: {
            confirmButton: "delybell-primary px-4",
            cancelButton: "delybell-dark",
          },
        });
    } catch (error) {
      console.error("Failed to change status of staff:", error);
    } finally {
      setIsLoading(false);
    }
  };
  // const handleChangePassword = () => {
  //   try {
  //   } catch (error) {
  //     console.error("Failed to change password of staff:", error);
  //   } finally {
  //     setIsLoading(false);
  //   }
  // };
  // const handleEdit = (details: any) => { }
  const handleView = (details: any) => { 
    router.push(`${window.location.pathname}?id=${details?.id}`);
    setShipmentDetails(details);
    setStep(2)
    toggle();
    // setStep
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handlePrint = (details: any) => { }
  const handleClearUrlPrams = () => router.push(`${window.location.pathname}`)

  const hasActiveFilters = () => {
    for (const key in shipmentFilters) {
      const value = shipmentFilters[key];
      if (typeof value === 'object' && value !== null) {
        // Handle date range objects
        if (('start' in value && value.start !== '') || ('end' in value && value.end !== '')) {
          return true;
        }
      } else if (value !== '' && value !== null && value !== undefined) {
        return true;
      }
    }
    return false;
  };

  const getFilterBadges = () => {
    const badges: { label: string; type: string }[] = [];
  
    // Shipment ID
    if (shipmentFilters.shipmentId) {
      badges.push({
        label: `Shipment ID: ${shipmentFilters.shipmentId}`,
        type: "shipmentId",
      });
    }
  
    // Status (enum mapping)
    if (shipmentFilters.status) {
      const statusLabel =
        ShipmentStatus[shipmentFilters.status as keyof typeof ShipmentStatus];
      badges.push({
        label: `Status: ${statusLabel}`,
        type: "status",
      });
    }
  
    // Type (enum mapping)
    if (shipmentFilters.type) {
      const typeLabel =
        ShipmentTypeForCustomer[
          shipmentFilters.type as keyof typeof ShipmentTypeForCustomer
        ];
      badges.push({
        label: `Type: ${typeLabel}`,
        type: "type",
      });
    }
  
    // Shipment Type for Admin (string value?)
    if (shipmentFilters.shipmentTypeForAdmin) {
      badges.push({
        label: `Shipment Type: ${shipmentFilters.shipmentTypeForAdmin}`,
        type: "shipmentTypeForAdmin",
      });
    }
  
    // Mode (enum mapping)
    if (shipmentFilters.mode) {
      const modeLabel =
        ShipmentMode[shipmentFilters.mode as keyof typeof ShipmentMode];
      badges.push({
        label: `Mode: ${modeLabel}`,
        type: "mode",
      });
    }
  
    // Shipment Date Range
    if (
      shipmentFilters.shipmentDateRange?.start ||
      shipmentFilters.shipmentDateRange?.end
    ) {
      badges.push({
        label: `Shipment Date: ${shipmentFilters.shipmentDateRange.start || ""} - ${
          shipmentFilters.shipmentDateRange.end || ""
        }`,
        type: "shipmentDateRange",
      });
    }
  
    // ETA Date Range
    if (
      shipmentFilters.etaDateRange?.start ||
      shipmentFilters.etaDateRange?.end
    ) {
      badges.push({
        label: `ETA Date: ${shipmentFilters.etaDateRange.start || ""} - ${
          shipmentFilters.etaDateRange.end || ""
        }`,
        type: "etaDateRange",
      });
    }
  
    return badges;
  };
  

  const clearIndividualFilter = (type: string) => {
    const newFilters = { ...shipmentFilters };
    if (type === 'shipmentDateRange' || type === 'etaDateRange') {
      newFilters[type] = { start: '', end: '' };
    } else {
      newFilters[type] = '';
    }
    setShipmentFilters(newFilters);
  };

  const handleClearAllFilters = () => {
    setShipmentFilters({
      shipmentId: "",
      status: "",
      type: "",
      shipmentTypeForAdmin: "",
      mode: "",
      shipmentDateRange: {
        start: "",
        end: "",
      },
      etaDateRange: {
        start: "",
        end: "",
      },
    });
  };

  useEffect(() => {
    fetchOrders();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shipmentFilters]);
  return (
    <>
      {isLoading && <HourGlassLoader />}
      <div className="page-content innerPageWrap ordersPageWrap oder-list-page">
        <div className="header header-fixed header-logo-app innerHeader">
          <a className="header-title header-subtitle">Shipments</a>
          <Link href="/dashboard" className="header-icon header-icon-1">
            <i className="fas fa-chevron-left" />
          </Link>
          {/* <button
            type="button"
            className="color-theme show-on-theme-light header-icon header-icon-2 font-16"
            onClick={() => setAddUserModal(true)}
          >
        <i className="fas fa-plus" />
</button> */}

          <div
            className="d-float-center justify-content-end"
            style={{ marginTop: "6px" }}
          >
              <button
    type="button"
    className="btn btn-s bg-green-dark rounded-s me-2"
    onClick={toggleFilter} // replace with toggleFilter()
  >
    <i className="fa fa-filter" /> {` `}
    Filter
  </button>
            <button
              type="button"
              className="btn btn-s bg-blue-dark rounded-s me-2"
              onClick={() => {
                handleClearUrlPrams()
                setAddUserModal(true); setStep(1)
              }}
            >
              <i className="fas fa-plus" />
              {` `}{shipmentDetails?.id ? 'Create' : 'Create'} Shipment
            </button>
            {/* <button
              type="button"
              className="btn btn-s bg-blue-dark rounded-s me-2"
              onClick={toggleShipmentView}
            >
              <i className="fas fa-eye" />
              {` `}View shipment
            </button> */}
          </div>
        </div>

        <div className="innerContentWrap orders-list">
          <div className="card card-style bg-transparent pb-0 m-0 rounded-0 overflow-visible">
          {hasActiveFilters() && (
          <div className="clear-filter-badge d-float-center justify-content-end">
            {getFilterBadges().map((badge, index) => (
              <div
                key={index}
                className="badge rounded-s d-float-center bg-blue-dark"
                role="clear"
              >
                <strong className="alert-icon-text color-white ps-1">
                  {badge.label}
                </strong>
                &nbsp;|&nbsp;
                <i
                  className="fa fa-times font-14"
                  onClick={() => clearIndividualFilter(badge.type)}
                ></i>
              </div>
            ))}
            <div
              className="badge rounded-s d-float-center bg-red-dark ms-2"
              role="clear"
              onClick={handleClearAllFilters}
            >
              <i className="fa fa-times font-14"></i>&nbsp;|&nbsp;
              <strong className="alert-icon-text color-white ps-0">
                Clear All
              </strong>
            </div>
          </div>
        )}
            <div className="content m-0">
              <div className="row my-orders-row">
                {users?.length > 0 ? (
                  <ShipmentCard shipments={users || []}  handleEdit={handleEdit} handleView={handleView} handlePrint={handlePrint}/>
                ) : (
                  <NoData />
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
      {addUserModal && (
        <Modal
          show={addUserModal}
          onHide={toggle}
          header={false}
          title=""
          fullscreen={"md"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <OverView onClose={toggle} step={step} setStep={setStep} shipmentDetails={shipmentDetails} setShipmentDetails={setShipmentDetails}/>
        </Modal>
      )}
      {filterModal && (
        <Modal
          show={filterModal}
          onHide={toggleFilter}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <ShipmentFilter
            onHide={toggleFilter}
            onSaveFilter={(filter: any) => {
              setShipmentFilters(filter);
              toggleFilter();
            }}
            initialFilters={shipmentFilters}
          />
        </Modal>
      )}
      {viewShipmentModal && (
        <Modal
          show={viewShipmentModal}
          onHide={toggleShipmentView}
          header={false}
          title=""
          fullscreen={"md"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <div
            id="menu-wizard-step-1"
            className="menu menu-box-right bg-white sendPackageBox menu-active"
            data-menu-height="cover"
            data-menu-width="cover"
          >
            <div
              className="card card-style bg-transparent shadow-0 mb-0 mx-3"
              style={{ height: "100%" }}
            >
              <div className="card-top mt-70">
                <div className="content mb-0 mt-0">
                  <ShipmentPreview />
                </div>
              </div>
            </div>
          </div>
        </Modal>
      )}
    </>
  );
}
