"use client";

import { createStore } from "zustand";
import { persist } from "zustand/middleware";

interface AppUiState {
  chats: {
    correspondenceStarted: {
      isVisibleAll: boolean;
    };
    newMessages: {
      isVisibleAll: boolean;
    };
  };
  home: {
    newMessages: {
      isVisibleAll: boolean;
    };
  };
  _hasHydrated: boolean;
}

export type AppUiActions = {
  setChats: (chats: AppUiState["chats"]) => void;
  setChatsCorrespondenceStarted: (
    correspondenceStarted: AppUiState["chats"]["correspondenceStarted"]
  ) => void;
  setChatsNewMessages: (
    newMessages: AppUiState["chats"]["newMessages"]
  ) => void;
  setHomeNewMessages: (newMessages: AppUiState["home"]["newMessages"]) => void;
  clearAppUiData: () => void;

  setHasHydrated: (hasHydrated: boolean) => void;
};

export type AppUiStore = AppUiState & AppUiActions;

const initialState: AppUiState = {
  chats: {
    correspondenceStarted: {
      isVisibleAll: true,
    },
    newMessages: {
      isVisibleAll: false,
    },
  },
  home: {
    newMessages: {
      isVisibleAll: false,
    },
  },
  _hasHydrated: false,
};

export const createAppUiStore = (initState: AppUiState = initialState) => {
  return createStore<AppUiStore>()(
    persist(
      (set, get) => ({
        ...initState,
        setChats: (chats: AppUiState["chats"]) => set({ chats }),

        setChatsCorrespondenceStarted: (
          correspondenceStarted: AppUiState["chats"]["correspondenceStarted"]
        ) =>
          set({
            chats: {
              ...get().chats,
              correspondenceStarted,
            },
          }),

        setChatsNewMessages: (
          newMessages: AppUiState["chats"]["newMessages"]
        ) =>
          set({
            chats: {
              ...get().chats,
              newMessages,
            },
          }),

        setHomeNewMessages: (newMessages: AppUiState["home"]["newMessages"]) =>
          set({ home: { ...get().home, newMessages } }),

        clearAppUiData: () => set(initialState),

        setHasHydrated: (hasHydrated: boolean) =>
          set({ _hasHydrated: hasHydrated }),
      }),
      {
        name: "app-ui-storage",
        onRehydrateStorage: () => state => {
          if (state) {
            state.setHasHydrated(true);
          }
        },
      }
    )
  );
};
