import {menuStore} from '@stores';
import {ParseMenuType} from '@utils';
import {useEffect, useState} from 'react';
import {useLocation, useNavigate} from 'react-router-dom';
import {useStore} from 'zustand';

export function useOpenKey(menus: ParseMenuType[]) {
  const navigate = useNavigate();
  const {pathname} = useLocation();
  const pages = useStore(menuStore, state => state.menus);

  const [current, setCurrent] = useState<string[]>(function() {
    const firstKey = menus[0]?.children ? menus[0].children[0].key : menus[0].key;

    return [firstKey];
  });
  const [openKeys, setOpenKey] = useState<string[]>(current);

  function onOpenChange(keys: string[]) {
    setOpenKey([keys[keys.length - 1]]);
  }

  function onClick(e: {key: string, keyPath: string[]}) {
    setOpenKey(e.keyPath);
    const data = pages.find(val => val.id === e.key);
    if (!data) return;

    navigate(data.url);
  }

  useEffect(function() {
    const route = pages.find(val => val.url === pathname);
    if (!route) return;

    if (route.id !== current[0]) setCurrent([route.id]);
  }, [current, pages, pathname]);

  return [{openKeys, current}, {onOpenChange, onClick}] as const;
}
