/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import { usePopup } from "@/context/PopupContext";
import BottomSheetModal from "../../Modal/BottomSheetModal";
import Modal from "../../Modal/Modal";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import LoginModal from "../../Modal/LoginModal";
import { useAppDispatch, useAppSelector } from "@/Redux/Hooks";
import { saveStepData } from "@/Redux/Reducers/CreateOrderSlice";
import ServiceTypeSelector from "../../pages/CreateOrder/Containers/Step1/ServiceTypeSelector";
const MenuModal = dynamic(() => import("../../Modal/MenuModal"), {
  ssr: false,
});
import Cookies from "js-cookie";
import HourGlassLoader from "../../Loader/Loader";
import { getMasterList } from "../../../Api/MastersApi";
import { getOrders } from "../../../Api/OrderApi";
import { serviceIconMap } from "@/Constant/enums";
import { checkPrimaryAddressAvailable } from "../../../lib/Helper";
import Swal from "sweetalert2";

const Footer: React.FC = () => {
  const { showPopup, closePopup } = usePopup();
  const pathname = usePathname();
  const [isLoading, setIsLoading] = useState(false);
  const [showOrderModal, setShowOrderModal] = useState(false);
  const [showProfileModal, setShowProfileModal] = useState(false);

  const handleOrderModalClose = () => setShowOrderModal(false);
  const handleOrderModalOpen = () => setShowOrderModal(true);

  const handleProfileModalOpen = () => setShowProfileModal(true);
  const handleProfileModalClose = () => setShowProfileModal(false);

  const isActive = (path: string): boolean => pathname === path;
  const [isPinned, setIsPinned] = useState<boolean>(false);
  const [openLoginModal, setOpenLoginModal] = useState<boolean>(false);
  const togglePin = () => {
    const newPinState = !isPinned;
    setIsPinned(newPinState);
    localStorage.setItem("menuModalPinned", newPinState.toString());
  };
  const toggleLogin = () => {
    const newPinState = !openLoginModal;
    setOpenLoginModal(newPinState);
  };

  const clearData = () => {
    if (typeof window !== "undefined") {
      localStorage.removeItem("AUTH_TOKEN");
      localStorage.removeItem("ROLE");
      localStorage.removeItem("ROLE_NAME");
      localStorage.removeItem("F_NAME");
      localStorage.removeItem("L_NAME");
      localStorage.removeItem("USER_ID");
      Cookies.remove("AUTH_TOKEN");
    }
  };

  const dispatch = useAppDispatch();
  interface CreateOrderState {
    step1: Record<string, any>;
    step2: Record<string, any>;
    step3: Record<string, any>;
    orderId?: string;
  }
  const createOrderData = useAppSelector(
    (state: { createOrder: CreateOrderState }) => state.createOrder
  );
  const [showServiceTypeSelector, setShowServiceTypeSelector] = useState(false);
  type ServiceType = { id: number; name: string };
  const [serviceTypes, setServiceTypes] = useState<ServiceType[]>([]); // Replace with actual fetch if needed
  const [serviceType, setServiceType] = useState<ServiceType | null>(null);
  const [serviceTypeError, setServiceTypeError] = useState<string>("");
  const [allowedServiceTypeId, setAllowedServiceTypeId] = useState<
    number | null
  >(null);
  const router = useRouter();
  useEffect(() => {
    const fetchMasterLists = async () => {
      try {
        setIsLoading(true);
        const [services] = await Promise.all([getMasterList("service_type")]);
        setServiceTypes(services.data || []);
      } catch (err) {
        console.error("Error loading masterlists", err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchMasterLists();
  }, []);

  // Fetch service types if needed (mock or real fetch)
  // useEffect(() => { setServiceTypes([...]); }, []);

  const handleCreateOrderClick = () => {
    if (checkPrimaryAddressAvailable()) {
        setShowServiceTypeSelector(true);
    } else {
      Swal.fire({
        icon: "error",
        title: "Profile Incomplete",
        text: "Please complete your profile by adding an pickup address before creating an order.",
        customClass: {
          confirmButton: "delybell-primary px-4",
          cancelButton: "delybell-dark",
        },
        buttonsStyling: true,
        showCancelButton: true,
        reverseButtons: true,
        cancelButtonText: "Cancel",
        confirmButtonText: "Go to Profile",
      }).then((result) => {
        if (result.isConfirmed) {
          router.push("/my-profile");
        }
      });
    }
  };
  const handleDomesticClick = () => {
    handleCreateOrderClick()
  };

  const handleInternationalClick = () => {
    setShowOrderModal(false)
    router.push('/create-international-order')
  }

  const handleServiceTypeChange = (serviceName: string | null) => {
    if (serviceName === null) {
      setServiceType(null);
      setServiceTypeError("Please select a service type");
    } else {
      const selected = serviceTypes.find((s) => s.name === serviceName);
      if (selected) {
        setServiceType(selected);
        setServiceTypeError("");
        dispatch(
          saveStepData({
            step: "step1",
            data: { ...createOrderData.step1, serviceType: selected },
          })
        );
        // setShowServiceTypeSelector(false); // Close selector after selection
      }
    }
  };
  const fetchOrders = async () => {
    setIsLoading(true);
    try {
      const orderList: any[] = await getOrders("draft", { limit: 1 });
      if (
        orderList &&
        orderList.length > 0 &&
        orderList[0].service_type_details
      ) {
        setServiceType(orderList[0].service_type_details);
        setAllowedServiceTypeId(orderList[0].service_type_details.id);
        dispatch(
          saveStepData({
            step: "step1",
            data: {
              ...createOrderData.step1,
              serviceType: orderList[0].service_type_details,
            },
          })
        );
      } else {
        setAllowedServiceTypeId(null);
      }
    } catch (error) {
      console.error("Failed to fetch orders:", error);
    } finally {
      setIsLoading(false);
    }
  };
  useEffect(() => {
    fetchOrders();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [showOrderModal]);
  return (
    <>
      <style>
        {`
        /* styles.css or globals.css */

.custom-center-modal.modal-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0 auto;
}
  .order-type-popup .interest-check:first-child { margin-left: -5px; }
  .modal-dialog-service-type .modal-content { padding: 0; }

        `}
      </style>
      {isLoading && <HourGlassLoader />}
      {/* Language Modal */}
      {showPopup && (
        <BottomSheetModal show={showPopup} onHide={closePopup} header={false}>
          <div className="menu-title">
            <p className="color-red2">{`We're multilingual`}</p>
            <h1 className="font-24">Choose your Language</h1>
          </div>

          <div className="me-4 ms-3 mt-0">
            <div className="list-group list-custom-small">
              <a href="#">
                <Image
                  className="me-3 mt-2"
                  src="/images/flags/United-States.png"
                  alt="United States Flag"
                  width={24}
                  height={16}
                />
                <span>English</span>
                <i className="fa fa-angle-right" />
              </a>
              <a href="#" className="border-bottom-0">
                <Image
                  className="me-3 mt-2"
                  src="/images/flags/uae.jpeg"
                  alt="UAE Flag"
                  width={24}
                  height={16}
                />
                <span>Arabic</span>
                <i className="fa fa-angle-right" />
              </a>
            </div>
          </div>
        </BottomSheetModal>
      )}

      {/* Footer Navigation */}
      <div id="footer-bar" className="footer-bar-6 text-uppercase">
        <Link
          href="/dashboard"
          className={isActive("/dashboard") ? "active-nav" : ""}
        >
          <i className="fa fa-home"></i>
          <span>Home</span>
          {isActive("/dashboard") && <em></em>}
        </Link>

        <Link
          href="/my-orders"
          className={isActive("/my-orders") ? "active-nav" : ""}
        >
          <i className="fa fa-cubes"></i>
          <span>Orders</span>
          {isActive("/my-orders") && <em></em>}
        </Link>

        <a
          onClick={handleOrderModalOpen}
          className="circle-nav d-lg-none"
          role="button"
        >
          <i className="fa fa-plus"></i>
          <span>Create Order</span>
          <strong>
            <u></u>
          </strong>
        </a>

        <Link
          href="/group-invoices"
          className={isActive("/group-invoices") ? "active-nav" : ""}
        >
          <i className="fa fa-file-invoice"></i>
          <span>Invoices</span>
          {isActive("/group-invoices") && <em></em>}
        </Link>

        <a
          onClick={handleProfileModalOpen}
          className={isActive("/profile") ? "active-nav" : ""}
          role="button"
        >
          <i className="fa fa-ellipsis-h" aria-hidden="true"></i>
          <span>More</span>
          {isActive("/profile") && <em></em>}
        </a>
        <a
          className={isActive("#") ? "active-nav" : "logout-menu mt-auto"}
          role="button"
          onClick={() => {
            Cookies.remove("AUTH_TOKEN");
            localStorage.clear(); // <-- Clear all localStorage data
            clearData();
            window.location.href = "/dashboard";
          }}
        >
          <i className="fa fa-sign-out" aria-hidden="true"></i>
          <span>Logout</span>
          {isActive("/profile") && <em></em>}
        </a>
      </div>
      <footer className="d-none d-lg-block footer-web">
        <a
          onClick={handleOrderModalOpen}
          className="circle-nav circle-nav-web"
          role="button"
          title="Create Order"
        >
          <i className="fa fa-plus"></i>
          <span className=" visually-hidden">Create Order</span>
          <strong>
            <u></u>
          </strong>
        </a>
      </footer>

      {/* Order Type Modal */}
      <Modal
        show={showOrderModal}
        onHide={() => {
          handleOrderModalClose();
          setShowServiceTypeSelector(false);
        }}
        header={false}
        title="Select order type"
        fullscreen={"lg"}
        centered={true}
        classname={showServiceTypeSelector ? "order-type-popup modal-dialog-service-type" : "modal-dialog-order-type"}
        position={"center"}
      >
        <div className="menu-title">
          <div>
            {/* <p class="color-highlight">Please choose your</p> */}
            <h3 className="choose-order-title">
              {showServiceTypeSelector ? "Domestic Order" : "Select order type"}
            </h3>
          </div>
          {/* <a href="#" class="close-menu"><i class="fa fa-times"></i></a> */}
        </div>

        <div className="divider tab-divider divider-margins"></div>

        <div className="choose-order-type">
          {showServiceTypeSelector ? (
            <>
              <h5 className="font-15 pb-1 ps-4">Select service type</h5>
              <div className="mt-3">
                <ServiceTypeSelector
                  serviceTypes={serviceTypes}
                  selectedServiceType={serviceType}
                  onChange={handleServiceTypeChange}
                  errors={{ serviceType: serviceTypeError }}
                  serviceIconMap={serviceIconMap}
                  allowedServiceTypeId={allowedServiceTypeId}
                />
              </div>
            </>
          ) : (
            <div className="d-float-center">
              <div className="ms-auto me-auto domestic text-center">
                <a
                  className="icon icon-l rounded-s"
                  onClick={handleDomesticClick}
                  role="button"
                >
                  <Image
                    className="order-icons img-fluid"
                    src="/images/icons/domestic-truck-p1.svg"
                    alt="Domestic Truck"
                    width={32}
                    height={32}
                  />
                  <br />
                </a>
                <p className="font-16 text-center">Domestic</p>
              </div>

              <div className="me-auto international text-center">
                <a href="#" className="icon icon-l rounded-s" onClick={handleInternationalClick}>
                  <Image
                    className="order-icons img-fluid"
                    src="/images/icons/international-flight-s1.svg"
                    alt="International Flight"
                    width={32}
                    height={32}
                  />
                  <br />
                </a>
                <p className="font-16 text-center">International</p>
              </div>
            </div>
          )}
        </div>
      </Modal>

      {/* Left Side Profile Modal */}
      {showProfileModal && (
        <Modal
          show={showProfileModal}
          onHide={handleProfileModalClose}
          header={false}
          // fullscreen="lg"
          centered={false}
          classname="left-slide-modal menu menu-box-left rounded-0 menu-active"
          position={"left"}
        >
          <MenuModal
            onHide={handleProfileModalClose}
            isPinned={isPinned}
            setIsPinned={setIsPinned}
            togglePin={togglePin}
            toggleLogin={toggleLogin}
          />
        </Modal>
      )}
      {openLoginModal && (
        <Modal
          show={openLoginModal}
          onHide={toggleLogin}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <LoginModal token={""} onClose={toggleLogin} />
        </Modal>
      )}
    </>
  );
};

export default Footer;
