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 { NavLink } from "react-router-dom";
import { MdLogout } 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";

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

  useEffect(() => {
    dispatch(accountSession());

    if (devices.length === 0) {
      dispatch(fetchDevices());
    }
  }, [dispatch, devices]);

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

  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">
          <GrMenu
            className="header__actions__icon"
            onClick={() => setIsSidebarOpen(true)}
          />

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

        <div className="header__devices">
          <CDeviceSelect
            devices={devices}
            selectedDevice={selectedDevice}
            onDeviceChange={(name) => dispatch(setSelectedDevice(name))}
            disabled={!devices.length}
            style={{ width: "220px" }}
            className="header__device-select"
          />
        </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={"/subscription"}
                  className={({ isActive }) => (isActive ? "active" : "")}
                  onClick={() => setIsSidebarOpen(false)}
                >
                  <BsCreditCard className="sidebard__content__navs__icon" />
                  <span>{t("navs.subscriptions")}</span>
                </NavLink>

                <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>
      )}
    </>
  );
};

export default Header;
