import { FC, useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { Group } from '../components';
import { notifications } from '../demoData/notification';
import { usePreferenceStore } from '../store';
import { twx } from '../utils';

interface HeaderButtonProps {
  className?: string;
  icon: string;
  onClick: () => void;
}

const HeaderButton: FC<HeaderButtonProps> = ({ className, icon, onClick }) => {
  return (
    <div
      className={twx(
        'h-9 w-9 cursor-pointer rounded p-2 transition-all hover:backdrop-brightness-90 dark:hover:backdrop-brightness-110 text-black/90 dark:text-white/90',
        className,
      )}
      onClick={onClick}
    >
      <div className={`w-full h-full  ${icon}`} />
    </div>
  );
};

export const Header: FC = () => {
  const navCollapsed = usePreferenceStore.use.navCollapsed();
  const navigate = useNavigate();
  const updatePreference = usePreferenceStore.use.updatePreference();
  const notifCenterCollapsed = usePreferenceStore.use.notifCenterCollapsed();
  return (
    <Group
      className={twx(
        `h-14 w-full gap-4 border-b bg-white border-black/10 text-black/90  px-4 text-xl shadow-lg dark:text-white/90 dark:bg-zinc-800 transition-all`,
        navCollapsed ? 'pl-20' : 'pl-62',
      )}
    >
      <Group className="flex-1 items-center gap-4">
        <p>SORI</p>
      </Group>
      <Group className="items-center gap-2">
        <IconButton
          iconClass="i-material-symbols-notifications-outline"
          count={notifications.length}
          onClick={() => {
            updatePreference({ notifCenterCollapsed: !notifCenterCollapsed });
          }}
          countClassName=" bg-red-5"
        />

        <HeaderButton
          icon={'i-mdi-exit-to-app'}
          onClick={() => {
            localStorage.clear();
            navigate('/login');
          }}
        />
      </Group>
    </Group>
  );
};

interface IconButtonProps {
  iconClass: string;
  count: number;
  onClick: () => void;
  countClassName: string;
}

const IconButton: FC<IconButtonProps> = ({
  iconClass,
  count,
  onClick,
  countClassName,
}) => {
  const [animateClose, setAnimateClose] = useState(false);
  useEffect(() => {
    setAnimateClose(true);
    const timeoutId = setTimeout(() => {
      setAnimateClose(false);
    }, 500);
    return () => clearTimeout(timeoutId);
  }, [count]);
  return (
    <div
      className={twx(
        'relative h-9 w-9 cursor-pointer rounded p-2 transition-all hover:backdrop-brightness-90 dark:hover:backdrop-brightness-110 dark:text-white/90',
        animateClose && 'animate-shock',
      )}
      onClick={onClick}
    >
      <div className={`w-full h-full ${iconClass}`} />
      <div
        className={twx(
          `absolute right-0  top-0 h-4 min-w-4 rounded-full ${countClassName} px-1 text-center text-xs text-white/90`,
        )}
      >
        {count}
      </div>
    </div>
  );
};
