/* 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, useRef, useState } from 'react';

import CardOverlayChip from '@/components/card/CardOverlayChip';
import Link from '@/components/link/Link';
import { PauseIcon, PlayIcon, ThumbsUpIcon } from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { getCountString } from '@/utils/utils';

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

export interface VideoHero {
  id: string;
  videoUrl: string;
  posterUrl?: string;
  title: string;
  artistName: string;
  playCount?: number;
  likeCount?: number;
}

interface VideoItemProps {
  onClick: () => void;
  video: VideoHero;
  handleLike?: () => void;
}

export const VideoItem = observer(({ video, handleLike }: VideoItemProps) => {
  const [localIsPlaying, setLocalIsPlaying] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const mediaStore = useMarketingStore();

  useEffect(() => {
    setLocalIsPlaying(
      mediaStore.videoStore.currentVideoId === video.id &&
        mediaStore.videoStore.isPlaying
    );
  }, [
    mediaStore.videoStore.currentVideoId,
    mediaStore.videoStore.isPlaying,
    video.id,
  ]);

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

    if (!videoRef.current) return;

    // update button UI
    setLocalIsPlaying(!localIsPlaying);

    logWebUserEvent({
      actionName: 'HomePageSongVideoClicked',
      context: {
        videoId: video.id,
      },
    });

    // handle video playback
    mediaStore.playVideo(video.id, videoRef.current);
  };

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

  const handleVideoEnd = () => {
    setLocalIsPlaying(false);
  };

  return (
    <div className='h-full w-full'>
      <div
        className='relative h-[415px] w-full origin-top rounded-[20px] transition-transform duration-300 hover:scale-[102%]'
        onClick={handlePlay}
      >
        <video
          ref={videoRef}
          src={video.videoUrl}
          className='h-full w-full rounded-[20px] object-cover'
          poster={video.posterUrl}
          playsInline
          preload='none'
          onEnded={handleVideoEnd}
        />

        {/* Play/Pause indicator at top left */}
        <div className='absolute top-[16px] left-[18px]'>
          {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 hidden flex-row gap-1'>
          <CardOverlayChip
            aria-label='Play button with play count'
            className='h-[30px] bg-[rgba(16,16,18,0.25)] text-[12.68px] leading-[15.216px] font-medium font-normal uppercase backdrop-blur-[15.22px]'
            onClick={handlePlay}
            onPointerUp={(
              e: React.PointerEvent<HTMLButtonElement | HTMLDivElement>
            ) => {
              e.preventDefault();
              e.stopPropagation();
            }}
            icon={<PlayIcon className='h-[14px] w-[14px]' />}
          >
            {video.playCount != null && getCountString(video.playCount)}
          </CardOverlayChip>
          <CardOverlayChip
            className='hidden h-[30px] bg-[rgba(16,16,18,0.25)] text-[12.68px] leading-[15.216px] font-medium font-normal uppercase backdrop-blur-[15.22px] md:flex'
            aria-label='Like button with like count'
            onClick={handleLikeClick}
            onPointerUp={(
              e: React.PointerEvent<HTMLButtonElement | HTMLDivElement>
            ) => {
              e.preventDefault();
              e.stopPropagation();
            }}
            icon={<ThumbsUpIcon className='h-[14px] w-[14px]' />}
          >
            {video.likeCount != null && getCountString(video.likeCount)}
          </CardOverlayChip>
        </div>
      </div>
      <div className='mt-[15px] cursor-pointer overflow-hidden text-[15.581px] leading-[15.581px] font-medium text-ellipsis whitespace-nowrap text-white'>
        <Link
          href={`https://instagram.com/${video.title}`}
          target='_blank'
          rel='noopener noreferrer'
          onClick={(e) => e.stopPropagation()}
          className='hover:underline'
        >
          @{video.title}
        </Link>
      </div>
    </div>
  );
});
