import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { MenuCategoryProps } from '../model/types';
import { useStore } from '@/shared/model/store';
import { IMAGE_ROOT } from '@/shared/constants/common';

export const MenuCategory = ({
  menuId,
  menuIcon,
  menuName,
  subMenu,
  setMenuOn,
  favoriteEdit
}: MenuCategoryProps) => {
  const { navigate } = useNavigate();

  const onClickToNavigate = (path?: string) => {
    if(!!path && !!setMenuOn && !favoriteEdit){
      setMenuOn(false);
      navigate(path);
    }
  };

  const favoriteSetting = (
    checked: boolean,
    title?: string,
    path?: string
  ) => {
    useStore.getState().UserStore.setUserFavorite([{
      title: title,
      img: IMAGE_ROOT + '/ico_menu_01.svg',
      path: path,
    }]);
  };

  const getMenuItems = () => {
    let rs = [];
    if(subMenu){
      for(let i=0;i<subMenu.length;i++){
        if(!!favoriteEdit){
          rs.push(
            <li
              key={ `menu-item-key-${menuId}-${i}` }
              onClick={ () => onClickToNavigate(subMenu[i]?.path) }
            >
              <span>{ subMenu[i]?.menuName }</span>
              <div className="check_box_scrap">
                <input 
                  id={ `menu-item-checkbox-${menuId}-${i}` }
                  className="checkbox"
                  type="checkbox" 
                  onChange={ (e) => favoriteSetting(e.target.checked, subMenu[i]?.menuName, subMenu[i]?.path) }
                />
                <label 
                  className="gtr"
                  htmlFor={ `menu-item-checkbox-${menuId}-${i}` }
                ></label>
              </div>
            </li>
          );
        }
        else{
          rs.push(
            <li
              key={ `menu-item-key-${i}` }
              onClick={ () => onClickToNavigate(subMenu[i]?.path) }
            >{ subMenu[i]?.menuName }</li>
          );
        }
        
      }
    }
    
    return rs;
  };

  return (
    <>
      <div className="menu-category">
        <div className="category-header">
          <div className={ 'category-icon ' + menuIcon }></div>
          <span>{ menuName }</span>
        </div>
        <ul className="category-items">
          { getMenuItems() }
        </ul>
      </div>
    </>
  );
};