import React, { useState, useRef, useEffect } from "react";
import "./Header.css";
import {
  IoNotificationsOutline,
  IoReload,
  IoSettingsOutline,
} from "react-icons/io5";
import { GrMenu } from "react-icons/gr";
import { Link, NavLink } from "react-router-dom";
import { MdLogout, MdNewspaper, MdSupportAgent } from "react-icons/md";
import { RiHome3Line } from "react-icons/ri";
import { BsCreditCard } from "react-icons/bs";
import { useTranslation } from "react-i18next";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import { accountSession } from "../../stores/slices/accountSlice";
import { FaUserAlt } from "react-icons/fa";
import { formatToDDMMYYYY } from "../../utils/utils";
import {
  fetchDevices,
  setSelectedDevice,
} from "../../stores/slices/deviceSlice";
import CDeviceSelect from "../../components/CDeviceSelect";
import { logout } from "../../stores/slices/authSlice";
import TheCybernanny from "../../assets/images/TheCybernanny.png";
import CButton from "../../components/CButton";
import CInfo from "../../components/CInfo";

const Header: React.FC = () => {
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isOpenInfoModal, setIsOpenInfoModal] = useState(false);
  const sidebarRef = useRef<HTMLDivElement>(null);
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  const { session } = useAppSelector((state: RootState) => state.account);
  const { devices, selectedDevice, isFetched } = useAppSelector(
    (state: RootState) => state.device
  );

  useEffect(() => {
    dispatch(accountSession());
  }, [dispatch]);

  useEffect(() => {
    if (!isFetched) {
      dispatch(fetchDevices());
    }
  }, [dispatch, isFetched]);

  const handleOutsideClick = (e: MouseEvent) => {
    if (sidebarRef.current && !sidebarRef.current.contains(e.target as Node)) {
      setIsSidebarOpen(false);
    }
  };

  const toggleInfoModal = () => {
    setIsOpenInfoModal((prev) => !prev);
  };

  useEffect(() => {
    if (isSidebarOpen) {
      document.addEventListener("mousedown", handleOutsideClick);
    } else {
      document.removeEventListener("mousedown", handleOutsideClick);
    }

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

  return (
    <>
      <div className="header wrapper">
        <div className="header__actions">
          <Link to={"/home"} className="header__actions__logo">
            <img src={TheCybernanny} alt="TheCybernanny" />
          </Link>

          <GrMenu
            className="header__actions__icon"
            onClick={() => setIsSidebarOpen(true)}
          />

          <IoReload
            className="header__actions__icon"
            onClick={() => window.location.reload()}
          />
        </div>

        <div className="header__devices">
          {devices.length > 0 ? (
            <CDeviceSelect
              devices={devices}
              selectedDevice={selectedDevice}
              onDeviceChange={(name) => dispatch(setSelectedDevice(name))}
              disabled={!devices.length}
              style={{ width: "220px" }}
              className="header__device-select"
              placeholder={t("common.selectDevice")}
            />
          ) : (
            <CButton
              title={t("help.howToStart")}
              onClick={toggleInfoModal}
              variant="primary"
            />
          )}
        </div>
      </div>

      {isSidebarOpen && (
        <div className="sidebar__overlay">
          <div className="sidebar" ref={sidebarRef}>
            <div className="sidebar__content">
              <div className="sidebar__content__info">
                <FaUserAlt className="sidebar__content__info__icon" />

                <div className="text-bold">
                  <p>{session.login}</p>
                  <p>
                    {t("session.activeTill")}:{" "}
                    {session.subDateEnd ? (
                      <span className="text-success">
                        {formatToDDMMYYYY(session.subDateEnd)}
                      </span>
                    ) : (
                      <span className="text-danger">
                        {t("session.noSubscription")}
                      </span>
                    )}
                  </p>
                  <p>
                    {t("session.emailStatus")}:{" "}
                    {session.emailVerified ? (
                      <span className="text-success">
                        {t("session.verified")}
                      </span>
                    ) : (
                      <span className="text-danger">
                        {t("session.unVerified")}
                      </span>
                    )}
                  </p>
                </div>
              </div>

              <div className="sidebar__content__navs">
                <NavLink
                  to={"/home"}
                  className={({ isActive }) => (isActive ? "active" : "")}
                  onClick={() => setIsSidebarOpen(false)}
                >
                  <RiHome3Line className="sidebard__content__navs__icon" />
                  <span>{t("navs.home")}</span>
                </NavLink>

                <NavLink
                  to={"/notifications"}
                  className={({ isActive }) => (isActive ? "active" : "")}
                  onClick={() => setIsSidebarOpen(false)}
                >
                  <IoNotificationsOutline className="sidebard__content__navs__icon" />
                  <span>{t("navs.notifications")}</span>
                </NavLink>

                <NavLink
                  to={"/news"}
                  className={({ isActive }) => (isActive ? "active" : "")}
                  onClick={() => setIsSidebarOpen(false)}
                >
                  <MdNewspaper className="sidebard__content__navs__icon" />
                  <span>{t("navs.news")}</span>
                </NavLink>

                <NavLink
                  to={"/subscription"}
                  className={({ isActive }) => (isActive ? "active" : "")}
                  onClick={() => setIsSidebarOpen(false)}
                >
                  <BsCreditCard className="sidebard__content__navs__icon" />
                  <span>{t("navs.subscriptions")}</span>
                </NavLink>

                <a
                  href="https://t.me/cybernanny_support"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <MdSupportAgent className="sidebard__content__navs__icon" />
                  <span>{t("navs.support")}</span>
                </a>

                <NavLink
                  to={"/settings"}
                  className={({ isActive }) => (isActive ? "active" : "")}
                  onClick={() => setIsSidebarOpen(false)}
                >
                  <IoSettingsOutline className="sidebard__content__navs__icon" />
                  <span>{t("navs.settings")}</span>
                </NavLink>
              </div>
            </div>

            <div className="sidebar__logout" onClick={() => dispatch(logout())}>
              <MdLogout className="sidebar__logout__icon" />
              <span>{t("navs.logout")}</span>
            </div>
          </div>
        </div>
      )}

      <CInfo isOpen={isOpenInfoModal} onToggle={toggleInfoModal} />
    </>
  );
};

export default Header;
