import {getRoleMenu} from '@apis';
import {useContextSection} from '@hooks';
import {HOME_PATH} from '@routes';
import {menuStore} from '@stores';
import {useQuery} from '@tanstack/react-query';
import {MENU_COLLAPSED_STORAGE, ParseMenuType, sortMenu} from '@utils';
import {useBoolean, useLocalStorageState} from 'ahooks';
import {useEffect, useState} from 'react';
import {useLocation, useNavigate} from 'react-router-dom';
import {useStore} from 'zustand';
import {context} from '../context';

export function useMenu() {
  const setMenus = useStore(menuStore, state => state.setMenu);

  const {data} = useQuery({
    queryKey: [getRoleMenu.name],
    async queryFn() {
      const data = await getRoleMenu();

      if (data.msg === '200') {
        const finalMenu = [
          {
            id: '-1',
            name: '首页',
            url: HOME_PATH,
            pId: '0',
            page: 1,
            limit: 0,
            orderBy: '0',
            img: 'fenxibaobiao',
          },
          ...data.data,
        ];

        setMenus(finalMenu);
        return sortMenu(finalMenu);
      }

      throw new Error(data.errMsg);
    },
    suspense: true,
    cacheTime: Infinity,
    staleTime: Infinity,
  });

  return data!;
}

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],
  );

  useEffect(
    function () {
      pathname === HOME_PATH && setOpenKey([]);
    },
    [pathname],
  );

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

export function useMenuState() {
  const [openKeys, setOpenKey] = useState<string[]>(['-1']);

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

  const pages = useStore(menuStore, state => state.menus);
  const dispatch = useContextSection(context, state => state[1]);
  function onClick(e: {key: string; keyPath: string[]}) {
    setOpenKey(e.keyPath);
    const data = pages.find(val => val.id === e.key);
    if (!data) return;

    dispatch({
      type: 'ADD',
      payload: {key: data.id, url: data.url, label: data.name},
    });
  }

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

export function useCollapsedMenu() {
  const [storage, setStorage] = useLocalStorageState<'0' | '1' | undefined>(
    MENU_COLLAPSED_STORAGE,
  );
  const [state, {set}] = useBoolean(
    storage ? storage === '1' : window.innerWidth <= 1200,
  );

  function toggle() {
    setStorage(state ? '0' : '1');
    set(!state);
  }

  return [state, toggle] as const;
}
