import { create } from "zustand";
import { persist } from "zustand/middleware";
import { useDashboardTabStore } from "./dashboardTabStore";

interface UseUserProfileStore {
  profile?: Record<string, any> | null;
  setUserProfile: (profile: Record<string, any>) => void;
  clearProfile: () => void;
}

const arePermissionsEqual = (
  permissions1?: string[],
  permissions2?: string[]
): boolean => {
  if (!permissions1 && !permissions2) return true;
  if (!permissions1 || !permissions2) return false;
  if (permissions1.length !== permissions2.length) return false;

  const sorted1 = [...permissions1].sort();
  const sorted2 = [...permissions2].sort();

  return JSON.stringify(sorted1) === JSON.stringify(sorted2);
};

const areProfilesEqual = (
  currentProfile: Record<string, any> | null | undefined,
  newProfile: Record<string, any>
): boolean => {
  if (!currentProfile) return false;

  if (
    !arePermissionsEqual(currentProfile.permissions, newProfile.permissions)
  ) {
    return false;
  }

  const currentKeys = Object.keys(currentProfile).filter(
    (key) => key !== "permissions"
  );
  const newKeys = Object.keys(newProfile).filter(
    (key) => key !== "permissions"
  );

  if (currentKeys.length !== newKeys.length) return false;

  for (const key of currentKeys) {
    if (
      JSON.stringify(currentProfile[key]) !== JSON.stringify(newProfile[key])
    ) {
      return false;
    }
  }

  return true;
};

export const useUserProfileStore = create<UseUserProfileStore>()(
  persist(
    (set, get) => ({
      profile: null,
      setUserProfile: (profile) => {
        const currentProfile = get().profile;

        if (!currentProfile) {
          set({ profile });
          console.log("profile", profile);
          return;
        }

        if (!areProfilesEqual(currentProfile, profile)) {
          set({ profile });
          console.log("profile", profile);
        }
      },
      clearProfile: () => set({ profile: null }),
    }),
    { name: "userprofile" }
  )
);

interface UseUserStore {
  auth?: string;
  setUser: (args: { auth: string }) => void;
  logOut?: () => void;
}

export const useUserStore = create<UseUserStore>()(
  persist(
    (set) => ({
      auth: "",
      setUser: ({ auth }) => set({ auth }),
      logOut: () => {
        set({ auth: "" });
        useUserProfileStore.getState().clearProfile();
        useDashboardTabStore.getState().clearTabs();
      },
    }),
    {
      name: "user",
    }
  )
);
