import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { useStore } from '@/shared/model/store';
import { UserFavorite } from '@/entities/user/model/types';
import { RefObject, useEffect, useState } from 'react';
import { MenuItem } from '../model/types';
import { useTranslation } from 'react-i18next';
import { MenuItems } from '@/entities/common/model/constant';

export interface MenuCategoryProps {
  menuId?: number;
  menuName?: string;
  iconFilePath?: string;
  subMenu?: Array<MenuItem>;
  setMenuOn?: (menuOn: boolean) => void;
  editMode?: boolean;
  changeMenuId?: string;
  setChangeMenuId: (menuIdChecked?: string) => void;
  buttonRefs: RefObject<Array<HTMLDivElement>>;
  itemIndex: number;
};

export const MenuCategory = ({
  menuId,
  iconFilePath,
  menuName,
  subMenu,
  setMenuOn,
  editMode,
  changeMenuId,
  setChangeMenuId,
  buttonRefs,
  itemIndex
}: MenuCategoryProps) => {
  const { navigate } = useNavigate();
  const { i18n } = useTranslation();
  
  const [favoriteItems, setFavoriteItems] = useState<Array<UserFavorite>>([]);
  const [menuIds, setMenuIds] = useState<Array<number | undefined>>([]);

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

  const favoriteSetting = (
    checked: boolean,
    menuId?: number,
    menuName?: string,
    menuNameEng?: string,
    iconFilePath?: string,
    programPath?: string,
  ) => {
    let userFavorite = useStore.getState().UserStore.userFavorite;
    if(checked){
      // 즐겨찾기가 4개 이상일 경우 마지막 항목 제거
      if(userFavorite.length >= 4){
        userFavorite = userFavorite.slice(0, 3);
      }
      userFavorite = [
        ...userFavorite,
        {
          menuId: menuId,
          menuName: menuName,
          menuNameEng: menuNameEng,
          iconFilePath: iconFilePath,
          programPath: programPath
        }
      ];
    }
    else{
      // 즐겨찾기가 1개 남았을 때는 해제하지 않음
      if(userFavorite.length <= 1){
        callFavoiteItems();
        return;
      }
      userFavorite = userFavorite.filter((value, _) => {
        return value.menuId !== menuId
      });
    }
    useStore.getState().UserStore.setUserFavorite(userFavorite);
    setChangeMenuId(`${menuId}-${checked}`);
    callFavoiteItems();
    
  };

  const callFavoiteItems = () => {
    let userFavorite = useStore.getState().UserStore.userFavorite;
    setFavoriteItems(userFavorite);
    let newArr: Array<number | undefined> = userFavorite.map((value, _) => {
      return value.menuId;
    });
    setMenuIds(newArr); 
  };

  useEffect(() => {
    callFavoiteItems();
  }, []);

  useEffect(() => {
    callFavoiteItems();
  }, [changeMenuId]);

  useEffect(() => {
    if(menuIds.length > 0) {
      // callShortcutSave();
    }

  }, [menuIds]);

  const getMenuItems = () => {
    let rs = [];
    if(subMenu){
      for(let i=0;i<subMenu.length;i++){
        const displayName = i18n.language === 'en' && subMenu[i]?.menuNameEng
          ? subMenu[i]?.menuNameEng
          : subMenu[i]?.menuName;

        if(!!editMode && subMenu[i] && subMenu[i]?.menuId){
          rs.push(
            <li
              key={ `menu-item-key-${menuId}-${i}` }
              onClick={ () => onClickToNavigate(subMenu[i]?.programPath) }
            >
              <span>{ displayName }</span>
              <div className="check_box_scrap">
                <input
                  id={ `menu-item-checkbox-${subMenu[i]?.menuId}-${i}` }
                  className="checkbox"
                  type="checkbox"
                  checked={ menuIds.includes(subMenu[i]?.menuId)? true: false }
                  onChange={ (e) => favoriteSetting(
                    e.target.checked,
                    subMenu[i]?.menuId,
                    subMenu[i]?.menuName,
                    subMenu[i]?.menuNameEng,
                    subMenu[i]?.iconFilePath,
                    subMenu[i]?.programPath,
                  )}
                />
                <label
                  className="gtr"
                  htmlFor={ `menu-item-checkbox-${subMenu[i]?.menuId}-${i}` }
                ></label>
              </div>
            </li>
          );
        }
        else{
          rs.push(
            <li
              key={ `menu-item-key-${i}` }
              onClick={ () => onClickToNavigate(subMenu[i]?.programPath) }
            >{ displayName }</li>
          );
        }

      }
    }

    return rs;
  };

  const displayCategoryName = i18n.language === 'en'
    ? MenuItems.find(item => item.menuId === menuId)?.menuNameEng || menuName
    : menuName;

  return (
    <>
      <div
        className={`menu-category ${menuId}`}
        ref={ (element: HTMLDivElement) => {
          if (element) {
            buttonRefs.current[itemIndex] = element;
          }
        } }
      >
        <div className="category-header">
          <div className={ 'category-icon ' + iconFilePath }></div>
          <span>{ displayCategoryName }</span>
        </div>
        <ul className="category-items">
        { getMenuItems() }
        </ul>
      </div>
    </>
  );
};