'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 React, { useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';

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 ContinuedFromSongRow from '@/components/song/ContinuedFromSongRow';
import { useClipsByIds } from '@/hooks/useClipById';
import useDisclosure from '@/hooks/useDisclosure';
import { CaretDownIcon, CaretUpIcon } from '@/icons';
import { ContextType } from '@/logging/contextTypes';
import { ClipEntity } from '@/state/clipStore';
import { formatClipTitle } from '@/utils/clip';

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

const ExtendedFromDropdown = observer(
  ({
    clipHistoryIds,
    contextId,
    contextType,
  }: {
    clipHistoryIds: string[];
    contextId: string;
    contextType: ContextType;
  }) => {
    const { isOpen, onOpen, onClose } = useDisclosure();
    const dropdownRef = useRef<HTMLDivElement>(null);
    const buttonRef = useRef<HTMLDivElement>(null);
    const {
      playbar: playbarStore,
      queue: queueStore,
      clips: clipsStore,
    } = useStores();
    const [isHovered, setIsHovered] = useState(false);
    const statsigClient = useStatsigClient();
    const showCaptionsFeature = statsigClient.checkGate('web-captions');

    useEffect(() => {
      const handleClickOutside = (event: MouseEvent) => {
        if (
          dropdownRef.current &&
          !dropdownRef.current.contains(event.target as Node) &&
          buttonRef.current &&
          !buttonRef.current.contains(event.target as Node)
        ) {
          onClose();
        }
      };

      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }, [onClose]);

    const { clips: historyClips, isLoading: isHistoryClipsLoading } =
      useClipsByIds(clipHistoryIds);

    const handleToggle = (event: React.MouseEvent) => {
      if (historyClips.length <= 1) {
        return;
      }

      event.stopPropagation();
      if (isOpen) {
        onClose();
      } else {
        onOpen();
      }
    };

    const playClipOnClick = ({
      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]);
    };

    if (
      !historyClips ||
      historyClips.length <= 0 ||
      (!historyClips[0] && !isHistoryClipsLoading)
    ) {
      return null;
    }
    const originalClip = historyClips[0];

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

    return (
      <div className='relative'>
        <div
          ref={buttonRef}
          className={`flex flex-row items-center ${showCaptionsFeature ? 'bg-background-tertiary' : 'bg-background-primary'} hover:bg-background-tertiary ${isOpen ? 'rounded-t-lg' : 'rounded-lg'} cursor-pointer px-3 py-2`}
        >
          {isHistoryClipsLoading || !originalClip ? (
            <ClipLineageSkeleton label='Extended from' />
          ) : (
            <>
              <div
                className='relative h-[41px] w-[30px] overflow-hidden'
                onMouseEnter={() => {
                  setIsHovered(true);
                }}
                onMouseLeave={() => {
                  setIsHovered(false);
                }}
                onClick={() => {
                  playClipOnClick({
                    clipToPlay: originalClip,
                    contextId: originalClip.id,
                    contextType: ContextType.SongExtendedFrom,
                  });
                }}
              >
                {originalClip.imageUrl ? (
                  <ImageWithFallback
                    alt='Song Image'
                    className='h-[41px] w-[30px] shrink-0 rounded-sm object-cover'
                    src={originalClip.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
                onClick={handleToggle}
                className='flex flex-1 items-center overflow-hidden pl-3'
              >
                <div className='w-full'>
                  <div className='truncate font-sans text-[14px] leading-[16px] font-semibold'>
                    Extended from
                  </div>
                  <div className='overflow-hidden text-[14px] leading-[16px] hover:underline'>
                    <Link href={`/song/${originalClip.id}/`}>
                      <span className='block truncate'>
                        {formatClipTitle(
                          originalClip?.title,
                          originalClip?.metadata?.prompt
                        )}
                      </span>
                    </Link>
                  </div>
                </div>
              </div>
              {historyClips.length > 1 && (
                <div onClick={handleToggle} className='flex items-center pl-3'>
                  {isOpen ? (
                    <CaretUpIcon className='h-4 w-4 fill-primary' />
                  ) : (
                    <CaretDownIcon className='h-4 w-4 fill-primary' />
                  )}
                </div>
              )}
            </>
          )}
        </div>
        {isOpen &&
          ReactDOM.createPortal(
            <div
              className={`scrollbar-hide absolute w-full rounded-b-md p-4 pb-0 shadow-lg ${showCaptionsFeature ? 'bg-background-secondary' : 'bg-background-primary'} z-10000 hover:bg-background-tertiary`}
              style={{ top: '100%', left: 0 }}
              ref={dropdownRef}
            >
              {historyClips.map((clip, index) => (
                <ContinuedFromSongRow
                  key={index}
                  rowKey={clip.id}
                  clip={clipsStore.clipById[clip.id]}
                  partNumber={index + 1}
                  onPlay={() =>
                    playClipOnClick({
                      clipToPlay: clip,
                      contextId,
                      contextType,
                    })
                  }
                  isSongPage={false}
                />
              ))}
            </div>,
            buttonRef.current?.parentElement || document.body
          )}
      </div>
    );
  }
);

export default ExtendedFromDropdown;
