"use client";
import React, { useState, useRef, useEffect } from "react";
import SideItem from "./SideItem";
// import Link from "next/link";
// Define the Sidebar component with React.FC
import { useAppSelector, useAppDispatch } from "@/app/hooks/useDispatch";
import { toggleSidebar } from "@/app/redux/features/auth/authAction";
import { useSidebarData } from "@/app/hooks/useData";

const Sidebar: React.FC = () => {
  const { isSidebarOpen } = useAppSelector((state) => state.auth);
  const dispatch = useAppDispatch();
  const { data: translations } = useSidebarData();
  const t = translations || {};
  const [isCampaignSubMenuOpen, setCampaignSubMenuOpen] =
    useState<boolean>(false);
  const campaignsRef = useRef<HTMLDivElement>(null);

  const toggleCampaignSubMenu = (): void => {
    setCampaignSubMenuOpen(!isCampaignSubMenuOpen);
  };
  const toggleSidebarButton = (): void => {
    dispatch(toggleSidebar());
  };
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        campaignsRef.current &&
        !campaignsRef.current.contains(event.target as Node)
      ) {
        setCampaignSubMenuOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const campaigns = [
    {
      id: 1,
      name: t.Campaigns?.SEP_Campaigns || "SEP Campaigns",
      path: "/campaigns/sepCampaigns",
    },
    {
      id: 2,
      name: t.Campaigns?.City_Hub_Page || "City Hub Page",
      path: "/campaigns/eventhubCampaigns",
    },
    {
      id: 3,
      name: t.Campaigns?.Category_Page || "Category Page",
      path: "/campaigns/categoryCampaigns",
    },
  ];

  const formatCampaignName = (name: string) => {
    if (name === "Campaigns") return name;

    const parts = name.split(" ");
    if (parts.length > 1) {
      return (
        <>
          {parts.slice(0, -1).join(" ")}
          <br />
          {parts[parts.length - 1]}
        </>
      );
    }
    return name;
  };

  return (
    <div className="">
      <div className={`sidebar ${isSidebarOpen ? "open" : ""} bg-color`}>
        <button className="sidebar-toggle-button" onClick={toggleSidebarButton}>
          {isSidebarOpen ? "" : ""}
        </button>
        <div className="sidebar-content">
          <div className="nav-item mt-3">
            <SideItem
              to="/home"
              icon="/home.svg"
              text={t.Menu?.Home || "Home"}
            />
            <SideItem
              to="/settings"
              icon="/settings.png"
              text={t.Menu?.Settings || "Settings"}
            />
            <SideItem
              to="/events"
              icon="/events.png"
              text={t.Menu?.Events || "Events"}
              disabled={true}
            />

            <div className="mb-4 relative" ref={campaignsRef}>
              <div
                className="w-full rounded-md h penta-para cursor-pointer"
                onClick={toggleCampaignSubMenu}
              >
                <div>
                  <div>
                    <span
                      style={{ fontSize: "1.2rem" }}
                      className="flex justify-center"
                    >
                      <img
                        className="w-8"
                        src="/addnote.png"
                        alt={t.Alt_Text?.Campaigns || "Campaigns"}
                      />
                    </span>
                  </div>
                  <div className="flex justify-center penta-para">
                    <span className="penta-para">
                      {t.Menu?.Campaigns || "Campaigns"}
                    </span>
                  </div>
                </div>
              </div>

              {/* {isCampaignSubMenuOpen && (
                <div className="absolute left-full top-0 ml-2 bg-[#6931F7] shadow-lg rounded-2xl border border-gray-200 min-w-30 z-50 sidebar-submenu">
                  <div className="py-4">
                    {campaigns.map((campaign) => (
                      <div key={campaign.id} className="mb-3 px-3">
                        <div className="flex flex-col items-center text-center">
                          <Link 
                            href={campaign.path} 
                            className="w-full rounded-md"
                            onClick={() => setCampaignSubMenuOpen(false)}
                          >
                            <div>
                              <div>
                                <span
                                  style={{ fontSize: "1.2rem" }}
                                  className={`flex justify-center ${
                                    window.location.pathname === campaign.path ? "rounded-full p-4 bg-[#4825B7]" : ""
                                  }`}
                                >
                                  <img className="w-8" src="/addnote.png" alt={campaign.name} />
                                </span>
                              </div>
                              <div className="flex justify-center penta-para mt-1">
                                <span
                                  className={`penta-para text-white text-sm leading-tight ${
                                    window.location.pathname === campaign.path ? "font-semibold" : ""
                                  }`}
                                >
                                  {formatCampaignName(campaign.name)}
                                </span>
                              </div>
                            </div>
                          </Link>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )} */}
              {isCampaignSubMenuOpen && (
                <div className="absolute left-full top-0 ml-2 bg-[#6931F7] shadow-lg rounded-2xl border border-gray-200 min-w-30 z-50 sidebar-submenu">
                  <div className="py-4">
                    {campaigns.map((campaign) => (
                      <div key={campaign.id} className="mb-3 px-3">
                        <div className="flex flex-col items-center text-center">
                          <div
                            className="w-full rounded-md cursor-pointer"
                            onClick={() => {
                              // Handle navigation manually
                              window.location.href = campaign.path;
                              setCampaignSubMenuOpen(false);
                            }}
                          >
                            <div>
                              <div>
                                <span
                                  style={{ fontSize: "1.2rem" }}
                                  className={`flex justify-center ${
                                    window.location.pathname === campaign.path
                                      ? "rounded-full p-4 bg-[#4825B7]"
                                      : ""
                                  }`}
                                >
                                  <img
                                    className="w-8"
                                    src="/addnote.png"
                                    alt={campaign.name}
                                  />
                                </span>
                              </div>
                              <div className="flex justify-center penta-para mt-1">
                                <span
                                  className={`penta-para text-white text-sm leading-tight ${
                                    window.location.pathname === campaign.path
                                      ? "font-semibold"
                                      : ""
                                  }`}
                                >
                                  {formatCampaignName(campaign.name)}
                                </span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            <SideItem
              to="/subscription"
              icon="/subscription.png"
              text={t.Menu?.Subscription || "Subscription"}
              disabled={true}
            />
            {/* <SideItem to="/notifications" icon="/email.png" text="Notifications"  disabled={true}/> */}
            <SideItem
              to="/media"
              icon="/media.png"
              text={t.Menu?.Media || "Media"}
              disabled={true}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Sidebar;
