import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import { usePathname } from 'next/navigation';

import { useStores } from '@/app/(root)/AppProviders';
import { useOrpheusExperimentGroup } from '@/app/(root)/chat/hooks/useOrpheusExperimentGroup';
import MoreSongsPanel from '@/components/section/MoreSongsPanel';
import SongQueuePanel from '@/components/section/SongQueuePanel';
import ClipPreview from '@/components/song/ClipPreview';
import { usePreviewContext } from '@/context/PreviewContext';
import useParentClip from '@/hooks/useParentClip';

// All possible sidebar modes:
type SidebarMode =
  | 'clip-preview'
  | 'more-songs'
  | 'promo'
  | 'song-queue'
  | 'none';

// Hook to determine which to show:
const useSidebarMode = (
  previewClip: any,
  clipForSongRecs: any,
  showPromoContent: boolean,
  isSongPage: boolean,
  showSongQueue: boolean
): SidebarMode => {
  if (showSongQueue === true) {
    return 'song-queue';
  }

  if (previewClip && !isSongPage) {
    return 'clip-preview';
  }

  if (clipForSongRecs) {
    return 'more-songs';
  }

  if (showPromoContent) {
    return 'promo';
  }

  return 'none';
};

const SidebarContent = observer(() => {
  const { previewClip, setPreviewClip, previewInfillRange, clipForSongRecs } =
    usePreviewContext();

  const pathname = usePathname();

  const { session, clips, playbar } = useStores();

  const isSongPage = pathname.startsWith('/song/');
  const showSongQueue = playbar.showSongQueue;
  const { isControlGroup: isChatExpControlGroup } = useOrpheusExperimentGroup();
  const isChatExpEnabled = !isChatExpControlGroup;

  const { parentClip } = useParentClip({ clipId: previewClip?.id ?? '' });

  // Determine the current sidebar mode:
  const sidebarMode = useSidebarMode(
    previewClip,
    clipForSongRecs,
    false, // showPromoContent
    isSongPage,
    !!showSongQueue
  );

  // Render content based on the current mode
  const renderSidebarContent = () => {
    switch (sidebarMode) {
      case 'clip-preview':
        return (
          <ClipPreview
            clip={clips.clipById[previewClip?.id ?? '']}
            onCloseClipPreview={() => {
              setPreviewClip(null);
            }}
            parentClip={parentClip}
            infillRange={previewInfillRange || undefined}
          />
        );
      case 'more-songs':
        return (
          <MoreSongsPanel clip={clips.clipById[clipForSongRecs?.id ?? '']} />
        );
      case 'song-queue':
        return (
          <div
            className={clsx(
              'absolute inset-0 z-10 bg-background-primary',
              showSongQueue === true
                ? 'animate-slide-in-bottom'
                : showSongQueue === false
                  ? 'animate-slide-out-bottom'
                  : 'hidden'
            )}
            onAnimationStart={(e) => {
              if (e.animationName === 'slide-out-bottom') {
                e.currentTarget.classList.remove('hidden');
              }
            }}
            onAnimationEnd={(e) => {
              if (e.animationName === 'slide-out-bottom') {
                e.currentTarget.classList.add('hidden');
              }
            }}
          >
            <SongQueuePanel className='absolute inset-0' />
          </div>
        );
      default:
        return null;
    }
  };

  // If there's nothing to show, don't render the sidebar
  if (
    sidebarMode === 'none' ||
    ((pathname.startsWith('/create') || pathname.startsWith('/chat')) &&
      isChatExpEnabled)
  ) {
    return null;
  }

  return (
    <div
      className={clsx(
        'h-full w-[232px] max-w-[250px] min-w-[232px] min-[1350px]:max-w-[300px] 2xl:max-w-[350px]',
        'no-scrollbar hidden overflow-y-scroll bg-background-primary',
        {
          'xl:block': pathname.startsWith('/create'),
          'lg:block': !pathname.startsWith('/create'),
          'theme-dark': sidebarMode === 'promo',
        }
      )}
      style={{
        scrollbarWidth: 'none',
        width: session.previewInitialWidth,
      }}
    >
      <div className='relative h-full'>{renderSidebarContent()}</div>
    </div>
  );
});

export default SidebarContent;
