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

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

import CardOverlayChip from '@/components/card/CardOverlayChip';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import { PauseIcon, PlayIcon, ThumbsUpIcon } from '@/icons';
import { useApiClient } from '@/lib/apiClient';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { LARGE_IMAGE, SMALL_IMAGE } from '@/utils/constants';
import { getCountString } from '@/utils/utils';

import { useMarketingStore } from '../stores/MarketingStoreContext';

export interface SongHero {
  id: string;
  imageUrl: string;
  title: string;
  artistName: string;
  artistImageUrl: string;
  audioUrl: string;
  playCount: number;
  likeCount: number;
}

interface SongItemProps {
  song: SongHero;
  onClick: () => void;
  audioUrl: string;
  handleLike?: () => void;
  variant?: 'default' | 'background';
}

export const SongItem = observer(
  ({ song, handleLike, variant = 'default' }: SongItemProps) => {
    const [localIsPlaying, setLocalIsPlaying] = useState(false);
    const apiClient = useApiClient();
    const mediaStore = useMarketingStore();

    useEffect(() => {
      setLocalIsPlaying(
        mediaStore.audioStore.currentSongId === song.id &&
          mediaStore.audioStore.isPlaying
      );
    }, [
      mediaStore.audioStore.currentSongId,
      mediaStore.audioStore.isPlaying,
      song.id,
    ]);

    const handlePlay = async (e: React.MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();

      // Immediately update UI
      setLocalIsPlaying(!localIsPlaying);

      logWebUserEvent({
        actionName: 'HomePageSongClicked',
        context: {
          clipId: song.id,
        },
      });

      // Increment play count when starting to play
      if (!localIsPlaying) {
        try {
          const playCount = song.playCount || 0;
          const baseSampleFactor = 1;
          const playCountFactor = 100;
          const sampleFactor =
            baseSampleFactor + Math.floor(playCount / playCountFactor);

          apiClient.POST('/api/gen/{gen_id}/increment_play_count/v2', {
            params: { path: { gen_id: song.id } },
            body: { sample_factor: sampleFactor },
          });
        } catch (error) {
          console.error('Failed to increment play count:', error);
        }
      }

      // Then handle audio
      mediaStore.playAudio(song.id, song.audioUrl);
    };

    const handleLikeClick = (e: React.MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();

      handleLike?.();
    };

    if (variant === 'background') {
      return (
        <div className='h-full w-full'>
          <div
            className='relative h-full w-full origin-top overflow-hidden rounded-[12px] transition-transform duration-300 hover:scale-[102%] md:h-[311px]'
            onClick={handlePlay}
          >
            <ImageWithFallback
              className='h-full w-full object-cover'
              src={song.imageUrl}
              alt={song.title}
              imageSize={LARGE_IMAGE}
              loading='lazy'
            />

            {/* Bottom gradient overlay for text readability */}
            <div
              className='pointer-events-none absolute right-0 bottom-0 left-0 h-24'
              style={{
                background:
                  'linear-gradient(to top, rgba(16,16,18,0.85) 0%, rgba(16,16,18,0.6) 40%, transparent 100%)',
              }}
            />

            <div className='absolute inset-0 flex items-center justify-center'>
              <div className='flex h-16 w-16 items-center justify-center rounded-full border border-white/20 bg-background-smoke-dense'>
                {localIsPlaying ? (
                  <PauseIcon className='text-white/70' width={24} height={28} />
                ) : (
                  <PlayIcon className='text-white/70' width={24} height={28} />
                )}
              </div>
            </div>

            <div className='absolute right-[14px] bottom-[14px] left-[14px] z-10'>
              <div className='mb-1 text-[14px] leading-[16px] font-medium text-white text-shadow-lg'>
                {song.title}
              </div>
              <div className='flex items-center gap-[6px]'>
                <div className='h-[20px] w-[20px]'>
                  <ImageWithFallback
                    className='h-full w-full rounded-full'
                    src={song.artistImageUrl}
                    alt={song.artistName}
                    imageSize={SMALL_IMAGE}
                    loading='lazy'
                  />
                </div>
                <div className='text-[11px] leading-[14px] font-medium text-white/80 text-shadow-lg'>
                  {song.artistName}
                </div>
              </div>
            </div>
          </div>
        </div>
      );
    }

    // Default variant
    return (
      <div className='h-full w-full'>
        <div
          className='relative h-[267px] w-full origin-top overflow-hidden rounded-[12px] transition-transform duration-300 hover:scale-[102%] md:h-[311px]'
          onClick={handlePlay}
        >
          <ImageWithFallback
            className='h-full w-full object-cover'
            src={song.imageUrl}
            alt={song.title}
            imageSize={LARGE_IMAGE}
            loading='lazy'
          />

          {/* Play/Pause indicator at top left */}
          <div className='absolute top-[13px] left-[13px]'>
            {localIsPlaying ? (
              <PauseIcon className='text-white' width={18} height={21} />
            ) : (
              <PlayIcon className='text-white' width={18} height={21} />
            )}
          </div>

          {/* Stats at bottom */}
          <div className='absolute bottom-[13px] left-[14.5px] flex flex-row gap-1'>
            <CardOverlayChip
              aria-label='Play button with play count'
              className='h-[30px] bg-dumbo-50/25 text-[12.68px] leading-[15.216px] font-medium uppercase backdrop-blur-[15.22px]'
              //onClick={handlePlay} why is the the play count clickable?
              onPointerUp={(
                e: React.PointerEvent<HTMLButtonElement | HTMLDivElement>
              ) => {
                e.preventDefault();
                e.stopPropagation();
              }}
              icon={<PlayIcon className='h-[12px] w-[12px]' />}
            >
              {song.playCount != null && getCountString(song.playCount)}
            </CardOverlayChip>
            <CardOverlayChip
              className='hidden h-[30px] bg-dumbo-50/25 text-[12.68px] leading-[15.216px] font-medium uppercase backdrop-blur-[15.22px] md:flex'
              aria-label='Like button with like count'
              onClick={handleLikeClick} // why is the like count clickable?
              onPointerUp={(
                e: React.PointerEvent<HTMLButtonElement | HTMLDivElement>
              ) => {
                e.preventDefault();
                e.stopPropagation();
              }}
              icon={<ThumbsUpIcon className='h-[14px] w-[14px]' />}
            >
              {song.likeCount != null && getCountString(song.likeCount)}
            </CardOverlayChip>
          </div>
        </div>
        <div className='mt-[15px] overflow-hidden text-[15.581px] leading-[15.581px] font-medium text-ellipsis whitespace-nowrap text-white'>
          {song.title}
        </div>
        <div className='mt-[10px] flex items-center gap-[4px]'>
          <div className='h-[24px] flex-[0_0_24px]'>
            <ImageWithFallback
              className='h-full w-full rounded-full'
              src={song.artistImageUrl}
              alt={song.artistName}
              imageSize={SMALL_IMAGE}
              loading='lazy'
            />
          </div>
          <div className='flex-1 text-[11.685px] leading-[15.581px] font-medium'>
            {song.artistName}
          </div>
        </div>
      </div>
    );
  }
);
