import {create} from 'zustand';
import {useShallow} from 'zustand/react/shallow';
import {ProgressItem} from '@modules/chats/contexts/AudioPlayerContext';

type ProgressStateStore = {
  audioTracks: Record<string, ProgressItem>;
  setProgress: (id: string, progress: ProgressItem) => void;
  getProgress: (id: string) => ProgressItem;
  resetTrackProgress: (id: string) => void;
  resetStore: () => void;
};

export const defaultTrackProgress = {
  position: 0,
  duration: 0,
};

export const useTrackStateStore = create<ProgressStateStore>((set, get) => ({
  audioTracks: {},
  setProgress: (id: string, progress) =>
    set(state => ({
      audioTracks: {
        ...state.audioTracks,
        [id]: progress,
      },
    })),
  getProgress: (id: string) => get().audioTracks[id] ?? defaultTrackProgress,
  resetTrackProgress: (id: string) =>
    set(state => {
      const track = get().audioTracks[id];
      if (!track) {
        return {};
      }

      return {
        audioTracks: {
          ...state.audioTracks,
          [id]: {
            ...track,
            position: 0,
          },
        },
      };
    }),
  resetStore: () => {
    set({audioTracks: {}});
  },
}));

export const useCurrentTrack = (id: string): ProgressItem => {
  return useTrackStateStore(
    useShallow(state => {
      return state.audioTracks[id] ?? defaultTrackProgress;
    }),
  );
};
