import React, { useEffect, useState } from 'react';
import { mdiClose, mdiMinus, mdiPlus } from '@mdi/js';
import BaseIcon from './BaseIcon';
import AsideMenuList from './AsideMenuList';
import { MenuAsideItem } from '../interfaces';
import { useAppSelector } from '../stores/hooks';

const ASIDE_WIDTH_STORAGE_KEY = 'aside-width';
const DEFAULT_ASIDE_WIDTH = 320;
const MIN_ASIDE_WIDTH = 288;
const MAX_ASIDE_WIDTH = 400;
const ASIDE_WIDTH_STEP = 24;

type Props = {
  menu: MenuAsideItem[];
  className?: string;
  onAsideLgCloseClick: () => void;
};

export default function AsideMenuLayer({ menu, className = '', ...props }: Props) {
  const corners = useAppSelector((state) => state.style.corners);
  const asideStyle = useAppSelector((state) => state.style.asideStyle);
  const asideBrandStyle = useAppSelector((state) => state.style.asideBrandStyle);
  const asideScrollbarsStyle = useAppSelector((state) => state.style.asideScrollbarsStyle);
  const darkMode = useAppSelector((state) => state.style.darkMode);
  const { currentUser } = useAppSelector((state) => state.auth);
  const [asideWidth, setAsideWidth] = useState(DEFAULT_ASIDE_WIDTH);

  useEffect(() => {
    if (typeof window === 'undefined') return;

    const storedValue = Number(window.localStorage.getItem(ASIDE_WIDTH_STORAGE_KEY));
    if (!Number.isNaN(storedValue) && storedValue >= MIN_ASIDE_WIDTH && storedValue <= MAX_ASIDE_WIDTH) {
      setAsideWidth(storedValue);
    }
  }, []);

  useEffect(() => {
    if (typeof document === 'undefined') return;

    document.documentElement.style.setProperty('--aside-width', `${asideWidth}px`);

    if (typeof window !== 'undefined') {
      window.localStorage.setItem(ASIDE_WIDTH_STORAGE_KEY, String(asideWidth));
    }
  }, [asideWidth]);

  const handleAsideLgCloseClick = (e: React.MouseEvent) => {
    e.preventDefault();
    props.onAsideLgCloseClick();
  };

  const resizeAside = (direction: 'narrower' | 'wider') => {
    setAsideWidth((currentWidth) => {
      const nextWidth =
        direction === 'wider' ? currentWidth + ASIDE_WIDTH_STEP : currentWidth - ASIDE_WIDTH_STEP;

      return Math.min(MAX_ASIDE_WIDTH, Math.max(MIN_ASIDE_WIDTH, nextWidth));
    });
  };

  const organizationName =
    currentUser?.organizations?.name || currentUser?.organization?.name || 'Corporate workspace';

  return (
    <aside
      id="asideMenu"
      className={`${className} fixed top-0 z-40 flex h-screen w-56 overflow-hidden transition-position lg:py-3 lg:pl-3 xl:w-[var(--aside-width)]`}
    >
      <div
        className={`flex flex-1 flex-col overflow-hidden border border-white/10 shadow-2xl dark:bg-dark-900 ${asideStyle} ${corners}`}
      >
        <div className={`flex min-h-20 items-start justify-between gap-3 px-4 py-4 ${asideBrandStyle}`}>
          <div className="min-w-0 flex-1">
            <div className="text-[11px] font-semibold uppercase tracking-[0.24em] text-cyan-200/80">
              Gracey
            </div>
            <div className="mt-1 break-words text-base font-semibold leading-6 text-white">
              Corporate Stay Portal
            </div>
            <p className="mt-1 break-words text-sm leading-5 text-slate-300">{organizationName}</p>
          </div>

          <div className="flex items-center gap-1">
            <div className="hidden items-center gap-1 xl:flex">
              <button
                type="button"
                className="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-white/10 bg-white/5 text-slate-200 transition hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
                onClick={() => resizeAside('narrower')}
                disabled={asideWidth <= MIN_ASIDE_WIDTH}
                aria-label="Make sidebar narrower"
                title="Make sidebar narrower"
              >
                <BaseIcon path={mdiMinus} size="16" />
              </button>
              <button
                type="button"
                className="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-white/10 bg-white/5 text-slate-200 transition hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
                onClick={() => resizeAside('wider')}
                disabled={asideWidth >= MAX_ASIDE_WIDTH}
                aria-label="Make sidebar wider"
                title="Make sidebar wider"
              >
                <BaseIcon path={mdiPlus} size="16" />
              </button>
            </div>
            <button
              className="hidden p-2 text-slate-300 transition hover:text-white lg:inline-block xl:hidden"
              onClick={handleAsideLgCloseClick}
              type="button"
              aria-label="Close sidebar"
            >
              <BaseIcon path={mdiClose} />
            </button>
          </div>
        </div>

        <div
          className={`flex-1 overflow-y-auto overflow-x-hidden px-2 py-3 ${
            darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
          }`}
        >
          <AsideMenuList menu={menu} />
        </div>
      </div>
    </aside>
  );
}
