import React, { useEffect, useMemo, useState } from "react";

import "./sidebar-navigation-styles.scss";
import NavItem from "../nav-item/NavItem";
import { SelectOption, SidebarNavigationProps } from "@app/models/components";
import {
  APIKeyIcon,
  PremiumBadge,
  CloseIcon,
  DashboardIcon,
  DatasetLinkedIcon,
  HeaderSfSyncLogo,
  MenuIcon,
  PreferencesIcon,
  SettingsIcon,
  SupportIcon,
} from "@app/assets/images/icons";
import { useSettings } from "@settings/contexts/SettingsContext";
import { useBlockNavigation } from "@settings/contexts/NavigationContext";
import Select from "../select/Select";
import { Language } from "@app/models/global";
import { useLocation, useNavigate } from "react-router-dom";
import ConfigItem from "../config-item/ConfigItem";

const SidebarNavigation: React.FC<SidebarNavigationProps> = ({
  isMobileView,
}) => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [selectedConfig, setSelectedConfig] = useState<string>("");

  const { emptyConfigList, initialSettings, handleChangeSelection } =
    useSettings();
  const { isNavBlocked } = useBlockNavigation();
  const { is_premium: isPremium } = sfsyncData;

  const navigate = useNavigate();
  const localization = sfsyncI18n.data;

  const allConfig: any = useMemo(() => {
    return Object.keys(initialSettings?.config_list ?? {}).map((key) => {
      const itemName = initialSettings?.config_list?.[key]?.name
        ? initialSettings?.config_list?.[key]?.name
        : key;
      const itemImage =
        initialSettings?.config_list?.[key]?.profile_picture_url ?? "";

      const itemSlug = initialSettings?.config_list?.[key]?.page_slug ?? "";
      const itemUrl = initialSettings?.config_list?.[key]?.page_url ?? "";
      return {
        id: key,
        name: itemName,
        image: itemImage,
        slug: itemSlug,
        url: itemUrl,
      };
    });
  }, [initialSettings]);

  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
  };

  const handleNavLinkClick = () => {
    setIsMenuOpen(false);
  };

  const handleSelectedConfigChange = async (value: string) => {
    await handleChangeSelection(value);
    navigate("/grid-manager", {
      replace: true,
    });
  };

  useEffect(() => {
    setSelectedConfig(initialSettings?.selected_config ?? "");
  }, [initialSettings]);

  const handleSupportClick = () => {
    navigate("/dashboard/overview", {
      state: {
        startChat: true,
      },
    });
  };

  return (
    <nav>
      <div className={`sidebar ${isMobileView ? "sidebar--mobile" : ""}`}>
        <div className="sidebar__logo">
          {HeaderSfSyncLogo}
          {isPremium ? (
            PremiumBadge
          ) : (
            <h2>{localization.the_social_feed_sync}</h2>
          )}
        </div>
        {isMobileView && (
          <button onClick={toggleMenu} className="menu-icon">
            {isMenuOpen ? CloseIcon : MenuIcon}
          </button>
        )}
        <div
          className={`menu-list-container ${
            isMenuOpen ? "show-container" : ""
          }`}
        >
          <div className="sidebar__section">
            <div className="sidebar__section-header">{localization.dashboard}</div>
            <ul className="sidebar__menu">
              <li>
                <NavItem
                  onClick={handleNavLinkClick}
                  to="/dashboard/overview"
                  icon={DashboardIcon}
                  text={localization.dashboard_overview}
                  disabled={isNavBlocked}
                ></NavItem>
              </li>
              <li>
                <NavItem
                  onClick={handleNavLinkClick}
                  to="/dashboard/site-preferences"
                  icon={PreferencesIcon}
                  text={localization.dashboard_site_preferences}
                  disabled={isNavBlocked}
                ></NavItem>
              </li>
            </ul>
          </div>

          <div className="sidebar__section">
            <div className="sidebar__section-header">MANAGE</div>
            <ul className="sidebar__menu">
              <li>
                <NavItem
                  onClick={handleNavLinkClick}
                  to="/configuration"
                  icon={APIKeyIcon}
                  text={localization.configuration}
                  disabled={isNavBlocked}
                ></NavItem>
              </li>
              <li>
                <NavItem
                  onClick={handleNavLinkClick}
                  to="/settings"
                  icon={SettingsIcon}
                  text={localization.settings}
                  disabled={isNavBlocked}
                ></NavItem>
              </li>
              <li>
                <div
                  className="sidebar__menu-item"
                  onClick={handleSupportClick}
                  role="button"
                  tabIndex={0}
                >
                  <span className="sidebar__menu-icon">{SupportIcon}</span>
                  <span>Support</span>
                </div>
              </li>
            </ul>
          </div>

          {!isMobileView && !emptyConfigList && !!allConfig.length && (
            <div className="sidebar__section">
              <div className="sidebar__divider"></div>
              <div className="config-items-list">
                {allConfig.map((item: any) => (
                  <React.Fragment key={item.id}>
                    <ConfigItem
                      name={item.name}
                      image={item.image}
                      slug={item.slug}
                      url={item.url}
                      onClick={() => {
                        handleSelectedConfigChange(item.id);
                      }}
                    />
                    {selectedConfig === item.id && (
                      <div className="config-item-submenu">
                        <ul className="sidebar__menu">
                          <li>
                            <NavItem
                              onClick={handleNavLinkClick}
                              to="/grid-manager"
                              icon={DatasetLinkedIcon}
                              text={localization.grid_manager}
                              disabled={isNavBlocked || emptyConfigList}
                            ></NavItem>
                          </li>
                          <li>
                            <NavItem
                              onClick={handleNavLinkClick}
                              to={`/configuration/${item.id}`}
                              icon={SettingsIcon}
                              text={localization.settings}
                              disabled={isNavBlocked || emptyConfigList}
                            ></NavItem>
                          </li>
                        </ul>
                      </div>
                    )}
                  </React.Fragment>
                ))}
              </div>
              <div className="sidebar__divider"></div>
            </div>
          )}
        </div>
      </div>
    </nav>
  );
};

export default SidebarNavigation;
