import { InitialStateResponse } from '@/app';
import { LIMIT_TREE_LEVEL } from '@/constants';
import { apiQueryGroups } from '@/services/master/GroupController';
import { useModel } from '@umijs/max';
import { useCallback, useEffect, useRef, useState } from 'react';

type UseGetGroupsResult = {
  groups: MasterModel.GroupNode[] | null;
  groupMap: GroupMap;
  loading: boolean;
  getGroups: () => Promise<void>;
};

type GroupMap = Record<string, { name: string; code?: string }>;

function buildGroupMap(
  groups: MasterModel.GroupNode[],
  map: GroupMap = {},
): GroupMap {
  groups.forEach((g) => {
    map[g.id] = {
      name: g.name,
      code: g.metadata?.code,
    };
    if (g.children?.length) {
      buildGroupMap(g.children, map);
    }
  });
  return map;
}

export default function useGetGroups(): UseGetGroupsResult {
  const [groups, setGroups] = useState<MasterModel.GroupNode[] | null>(null);
  const [groupMap, setGroupMap] = useState<GroupMap>({});
  const [loading, setLoading] = useState(false);

  const { initialState } = useModel('@@initialState') as {
    initialState?: InitialStateResponse;
  };

  const currentUserProfile = initialState?.currentUserProfile;

  /**
   * ✅ FIX CACHE
   * Khi user đổi (logout / login user khác)
   * → clear groups cũ
   */
  const prevUserIdRef = useRef<string | null>(null);

  useEffect(() => {
    const currentUserId = currentUserProfile?.id ?? null;

    if (prevUserIdRef.current && prevUserIdRef.current !== currentUserId) {
      // user đổi → clear cache
      setGroups(null);
    }

    prevUserIdRef.current = currentUserId;
  }, [currentUserProfile?.id]);

  /**
   * ✅ GIỮ NGUYÊN LOGIC CŨ
   * chỉ thêm guard + dependency đúng
   **/
  const getGroups = useCallback(async (): Promise<void> => {
    if (!currentUserProfile?.id) return;

    setLoading(true);
    try {
      const tree = await apiQueryGroups({
        level: LIMIT_TREE_LEVEL,
        tree: true,
      });
      setGroups(tree?.groups || []);
      setGroupMap(buildGroupMap(tree?.groups || []));
    } catch (err) {
      console.error('Fetch data failed', err);
      setGroups([]);
    } finally {
      setLoading(false);
    }
  }, [currentUserProfile]);

  return {
    groups,
    groupMap,
    loading,
    getGroups,
  };
}
