import {create} from 'zustand';
import {useShallow} from 'zustand/react/shallow';
import {ChatUser, MediaEntity} from '@modules/chats/interfaces';

interface NewChatSharedDataState {
  members: ChatUser[];
  groupName: string;
  groupPicture: MediaEntity | null;

  // Actions
  setMembers: (users: ChatUser[]) => void;
  addMember: (user: ChatUser) => void;
  removeMember: (userId: string) => void;
  setGroupName: (name: string) => void;
  setGroupPicture: (file: Nullable<MediaEntity>) => void;
  clear: () => void;
}

const initialState = {
  members: [],
  groupName: '',
  groupPicture: null,
};

export const useNewChatSharedData = create<NewChatSharedDataState>(set => ({
  ...initialState,

  setMembers: (users: ChatUser[]) =>
    set(() => ({
      members: users,
    })),

  addMember: (user: ChatUser) =>
    set(state => {
      const exists = state.members.some(
        existingUser => existingUser.id === user.id,
      );
      if (exists) {
        return state;
      }
      return {
        members: [...state.members, user],
      };
    }),

  removeMember: (userId: string) =>
    set(state => ({
      members: state.members.filter(user => user.id !== userId),
    })),

  setGroupName: (name: string) =>
    set(() => ({
      groupName: name,
    })),

  setGroupPicture: (file: MediaEntity | null) =>
    set(() => ({
      groupPicture: file,
    })),

  clear: () =>
    set(() => ({
      members: [],
      groupName: '',
      groupPicture: null,
    })),
}));

export const useNewChatData = () => {
  return useNewChatSharedData(
    useShallow(state => ({
      members: state.members,
      groupName: state.groupName,
      groupPicture: state.groupPicture,
      setGroupName: state.setGroupName,
      setGroupPicture: state.setGroupPicture,
      removeMember: state.removeMember,
      clear: state.clear,
    })),
  );
};

export const useNewChatMembers = () => {
  return useNewChatSharedData(
    useShallow(state => ({
      members: state.members,
      setMembers: state.setMembers,
      clear: state.clear,
    })),
  );
};
