/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import { observer } from 'mobx-react-lite';
import { useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Link from '@/components/link/Link';
import { useContextSelector } from '@/hooks/useContextSelector';
import { PauseIcon, PlayIcon, SparklesIcon } from '@/icons';
import { TrashIcon } from '@/icons';
import { ContextType } from '@/logging/contextTypes';
import { Playlist } from '@/state/clipStore';
import { LARGE_IMAGE } from '@/utils/constants';
import { DEFAULT_AUDIO_WEIGHT_VALUE } from '@/utils/constants';

import CreateFormContext from '../v2/CreateFormContext';
import { ConditionTypes, CreateModes } from '../v2/types';

interface PlaylistConditionProps {
  playlist: Playlist;
}

export const PlaylistCondition = observer(
  ({ playlist }: PlaylistConditionProps) => {
    const { createV2, genForm, queue, playbar } = useStores();
    const [isHovered, setIsHovered] = useState(false);

    const setState = useContextSelector(
      CreateFormContext,
      (context) => context.setState
    );

    const handleClearPlaylistCondition = async () => {
      createV2.setConditioningPlaylist(null);
      genForm.setTask(null);
      genForm.resetMvToUserPreference();

      setState((prev) => {
        const { [ConditionTypes.PLAYLIST]: playlist, ...otherConditions } =
          prev.global.untimedConditions;
        return {
          ...prev,
          global: {
            ...prev.global,
            untimedConditions: otherConditions,
          },
          [CreateModes.CUSTOM]: {
            ...prev[CreateModes.CUSTOM],
            audioInfluence: DEFAULT_AUDIO_WEIGHT_VALUE,
          },
        };
      });
    };

    const isCurrent =
      queue.contextType === ContextType.Playlist &&
      queue.contextId === playlist.id;
    const isPlaying = playbar.isPlaying && isCurrent;

    const handlePlayPlaylist = () => {
      if (isCurrent && isPlaying) {
        playbar.togglePlay();
        return;
      }
      if (playlist?.playlist_clips?.length > 0) {
        queue.setPlayContext({
          contextType: ContextType.Playlist,
          contextId: playlist.id,
          clips: playlist.playlist_clips.map((pc: any) => pc.clip),
          currentIndex: 0,
        });
        playbar.playClip(playlist.playlist_clips[0].clip);
      }
    };

    return (
      <div className='h-auto w-auto rounded-[20px] bg-background-secondary p-4'>
        <div className='flex w-full flex-col gap-2'>
          <div className='flex w-full flex-row items-center justify-between'>
            <span className='flex flex-row items-center gap-2 font-sans font-medium'>
              <SparklesIcon className='h-5 w-5 text-primary' />
              Inspiration
              <span className='rounded-md bg-accent-pink px-1 py-0.5 text-xs font-medium text-foreground-primary-on-light'>
                NEW
              </span>
            </span>
            <Button
              variant={ButtonVariant.Secondary}
              shape={ButtonShape.Pill}
              size={ButtonSize.Mini}
              iconClassName='w-4 h-4'
              onClick={handleClearPlaylistCondition}
              icon={TrashIcon}
            />
          </div>
          <div className='flex w-full items-center justify-between'>
            <div className='flex items-center'>
              <div
                className='group relative h-12 w-12 cursor-pointer overflow-hidden rounded-lg'
                onClick={handlePlayPlaylist}
                title='Play playlist'
                onMouseEnter={() => setIsHovered(true)}
                onMouseLeave={() => setIsHovered(false)}
              >
                <ImageWithFallback
                  imageSize={LARGE_IMAGE}
                  className='h-full w-full object-cover'
                  src={playlist.image_url}
                  alt={`Playlist image for ${playlist.name}`}
                />
                {/* Play/Pause button overlay */}
                <div
                  className={`absolute inset-0 flex items-center justify-center transition-opacity duration-200 ${isHovered || isPlaying ? 'opacity-100' : 'opacity-0'} bg-black/40`}
                >
                  {isPlaying ? (
                    <PauseIcon className='h-5 w-5 text-foreground-primary' />
                  ) : (
                    <PlayIcon className='h-5 w-5 text-foreground-primary' />
                  )}
                </div>
              </div>
              <Link
                href={`/playlist/${playlist.id}`}
                className='ml-2 line-clamp-1 font-sans text-lg font-bold font-medium whitespace-pre-wrap hover:underline'
              >
                {playlist.name}
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }
);
