'use client';

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

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

import { useStores } from '@/app/(root)/AppProviders';
import CardPlayPauseButton from '@/components/button/CardPlayPauseButton';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Link from '@/components/link/Link';
import { SongMenuWithContext } from '@/components/song/newActions/SongMenuWithContext';
import { useClipById } from '@/hooks/useClipById';
import { ContextType } from '@/logging/contextTypes';
import { ClipEntity } from '@/state/clipStore';
import { formatClipTitle } from '@/utils/clip';

import {
  ClipLineageImageSkeleton,
  ClipLineageSkeleton,
} from './LineageCardSkeleton';

const ClipLineageCard = observer(
  ({
    label,
    compact,
    clipId,
    contextId,
    contextType,
  }: {
    label: string;
    clipId?: string;
    contextId: string;
    contextType: ContextType;
    compact?: boolean;
    onPlay?: () => void;
  }) => {
    const {
      playbar: playbarStore,
      queue: queueStore,
      clips: clipsStore,
    } = useStores();
    const [isHovered, setIsHovered] = useState(false);
    const statsigClient = useStatsigClient();
    const showCaptionsFeature = statsigClient.checkGate('web-captions');

    const isPlaying = queueStore.currentPlayingSongIsRemoved
      ? false
      : playbarStore.clip?.id === clipId && playbarStore.isPlaying;
    const showPlayPauseButton = isHovered || isPlaying;

    const margin = compact ? 'm-0' : 'm-4 mb-2 mt-3 ';

    const { data: clipData, isLoading } = useClipById(clipId);
    const fullClipData = clipData
      ? clipsStore.clipById[clipData.id]
      : undefined;

    if (!clipData && !isLoading) {
      return null;
    }

    const handlePlayClip = ({
      clipToPlay,
      contextId,
      contextType,
    }: {
      clipToPlay: ClipEntity | undefined;
      contextId: string;
      contextType: ContextType;
    }) => {
      if (!clipToPlay) return;
      if (
        queueStore.contextType === contextType &&
        queueStore.contextId === contextId &&
        playbarStore.clip?.id === clipToPlay.id
      ) {
        playbarStore.togglePlay();
        return;
      }
      queueStore.setPlayContext({
        contextType: contextType,
        contextId: contextId,
        currentIndex: clipsStore.clips.findIndex((c) => c.id === clipToPlay.id),
        clips: clipsStore.clips,
      });
      playbarStore.playClip(clipsStore.clipById[clipToPlay.id]);
    };

    return (
      <div>
        <div
          className={`${showCaptionsFeature ? 'bg-background-secondary' : 'bg-background-primary'} rounded-md px-3 py-2 font-sans hover:bg-background-secondary ${margin}`}
        >
          <div className='text-xs'>
            {isLoading ? (
              <ClipLineageSkeleton label={label} />
            ) : (
              clipData && (
                <div className='flex flex-row'>
                  <div
                    className='relative h-[41px] w-[30px] overflow-hidden'
                    onMouseEnter={() => {
                      setIsHovered(true);
                    }}
                    onMouseLeave={() => {
                      setIsHovered(false);
                    }}
                    onClick={() => {
                      handlePlayClip({
                        clipToPlay: clipData,
                        contextId: contextId,
                        contextType: contextType,
                      });
                    }}
                  >
                    {clipData.imageUrl ? (
                      <ImageWithFallback
                        alt='Song Image'
                        className='h-[41px] w-[30px] shrink-0 rounded-sm object-cover'
                        src={clipData.imageUrl}
                      />
                    ) : (
                      <ClipLineageImageSkeleton />
                    )}
                    <CardPlayPauseButton
                      className={clsx(
                        'absolute top-1/2 left-1/2 h-12 w-12 -translate-x-1/2 -translate-y-1/2 transform duration-300',
                        {
                          'scale-75 opacity-0': !showPlayPauseButton,
                          'scale-100 opacity-100': showPlayPauseButton,
                        }
                      )}
                      icon={
                        !isPlaying ? 'play' : isHovered ? 'pause' : 'playing'
                      }
                    />
                  </div>
                  <div className='flex flex-1 items-center overflow-hidden pl-3'>
                    <div className='w-full'>
                      <div className='font-sans text-[14px] leading-[16px] font-semibold'>
                        {label}
                      </div>
                      <div className='overflow-hidden text-[14px] hover:underline'>
                        <Link href={`/song/${clipId}/`}>
                          <span className='block truncate'>
                            {formatClipTitle(
                              clipData.title,
                              clipData.metadata?.prompt
                            )}
                          </span>
                        </Link>
                      </div>
                    </div>
                  </div>
                  <div className='flex items-center self-center'>
                    {fullClipData && (
                      <SongMenuWithContext clip={fullClipData} />
                    )}
                  </div>
                </div>
              )
            )}
          </div>
        </div>
      </div>
    );
  }
);

export default ClipLineageCard;
