import { noop } from 'lodash-es';
import { Dispatch, SetStateAction } from 'react';
import { useSessionStorage } from 'usehooks-ts';

import { useStores } from '@/app/(root)/AppProviders';
import { Clip } from '@/state/clipStore';

// keeps track of whether a clip has been played.
// state returned for the given clip is effectively global.
const useHasBeenPlayed = (
  clip: Clip | null
): [boolean, Dispatch<SetStateAction<boolean>>] => {
  const { session, playbar } = useStores();
  const [hasBeenPlayed, setHasBeenPlayed] = useSessionStorage(
    `hasBeenPlayed-aug-23-2025-${clip?.id}`,
    false
  );

  if (!clip) {
    return [false, noop];
  }

  const isProcessing =
    clip.status === 'queued' ||
    clip.status === 'submitted' ||
    clip.status === 'processing';

  return [
    !Boolean(
      clip.play_count === 0 &&
        (clip.reaction?.play_count || 0) === 0 &&
        !isProcessing &&
        !hasBeenPlayed &&
        session.user?.id === clip.user_id &&
        !playbar.recentlyPlayedIds.includes(clip.id)
    ),
    setHasBeenPlayed,
  ];
};

export default useHasBeenPlayed;
