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

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

import { useStores } from '@/app/(root)/AppProviders';
import { PERSONA_SHAPE_IMAGE } from '@/app/(root)/persona/[slug]/constants';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import CloseButton from '@/components/button/CloseButton';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Link from '@/components/link/Link';
import { PauseIcon, PersonaCreateIcon, PlayIcon, PlusIcon } from '@/icons';
import { ContextType } from '@/logging/contextTypes';
import { FALLBACK_IMAGE_URL, LARGE_IMAGE } from '@/utils/constants';

type Props = {
  hideWhenEmpty?: boolean;
};

export const PersonaSection = observer(({ hideWhenEmpty = false }: Props) => {
  const { createV2, genForm, playbar, queue, clips } = useStores();
  const [showPlayIcon, setShowPlayIcon] = useState(false);

  const handlePlayClip = (clipId: string) => {
    if (playbar.clip?.id === clipId) {
      playbar.togglePlay();
    } else {
      queue.setPlayContext({
        clips: [clips.clipById[clipId]].filter(Boolean),
        currentIndex: 0,
        contextType: ContextType.PersonaPreview,
        contextId: 'persona_section_preview',
      });
      playbar.playClip(clips.clipById[clipId]);
    }
  };

  return !createV2.activePersona && hideWhenEmpty ? null : (
    <div
      className={clsx(
        'h-auto w-full rounded-[20px] bg-background-secondary pr-4 pl-4',
        {
          'cursor-pointer py-3 hover:bg-background-tertiary':
            !createV2.activePersona,
          'py-1': !!createV2.activePersona,
        }
      )}
      onClick={() => {
        if (!createV2.activePersona) {
          createV2.setIsAddPopoverOpen(true);
          createV2.setAddMenuState('personas');
        }
      }}
    >
      <div className='flex w-full flex-row items-center justify-start py-2'>
        {!!createV2.activePersona ? (
          <div
            className='relative size-10 overflow-hidden'
            style={{
              mask: `url(${PERSONA_SHAPE_IMAGE})`,
              WebkitMask: `url(${PERSONA_SHAPE_IMAGE})`,
              maskSize: 'contain',
              WebkitMaskSize: 'contain',
              maskRepeat: 'no-repeat',
              WebkitMaskRepeat: 'no-repeat',
              maskPosition: 'center',
              WebkitMaskPosition: 'center',
            }}
            onMouseEnter={() => setShowPlayIcon(true)}
            onMouseLeave={() => setShowPlayIcon(false)}
          >
            <ImageWithFallback
              imageSize={LARGE_IMAGE}
              className='h-full w-full object-cover'
              src={
                createV2.activePersona?.clip?.image_url || FALLBACK_IMAGE_URL
              }
              alt={`Persona image for ${createV2.activePersona?.name}`}
            />
            <div
              className='absolute inset-0 flex items-center justify-center bg-black/50 transition-opacity duration-300'
              style={{
                opacity:
                  showPlayIcon ||
                  (playbar.clip?.id === createV2.activePersona?.root_clip_id &&
                    playbar.isPlaying)
                    ? 1
                    : 0,
              }}
            >
              <Button
                aria-label='Play'
                icon={
                  playbar.clip?.id === createV2.activePersona?.root_clip_id &&
                  playbar.isPlaying
                    ? PauseIcon
                    : PlayIcon
                }
                variant={ButtonVariant.Secondary}
                shape={ButtonShape.Pill}
                size={ButtonSize.Small}
                onClick={(e) => {
                  e.stopPropagation();
                  if (createV2.activePersona?.root_clip_id) {
                    handlePlayClip(createV2.activePersona.root_clip_id);
                  }
                }}
              />
            </div>
          </div>
        ) : (
          <PersonaCreateIcon />
        )}

        {!!createV2.activePersona ? (
          <div className='flex-1 pr-4 pl-4'>
            <Link
              href={`/persona/${createV2.activePersona?.id}`}
              className='line-clamp-4 font-sans text-lg font-medium whitespace-pre-wrap hover:underline'
            >
              {createV2.activePersona?.name}
            </Link>
          </div>
        ) : (
          <div className='flex-1 pl-[5px]'>
            <span className='font-sans font-medium'>Persona</span>
          </div>
        )}

        {!!createV2.activePersona ? (
          <CloseButton
            className='bg-transparent backdrop-blur-none'
            onClick={(e) => {
              createV2.setActivePersona(null);
              genForm.resetPersona();
              genForm.personaId = null;
              e.stopPropagation();
            }}
          />
        ) : (
          <Button
            variant={ButtonVariant.Glass}
            shape={ButtonShape.Pill}
            size={ButtonSize.Medium}
            className='bg-transparent'
            onClick={() => {
              if (!createV2.activePersona) {
                createV2.setIsAddPopoverOpen(true);
                createV2.setAddMenuState('personas');
              }
            }}
            icon={PlusIcon}
          />
        )}
      </div>
    </div>
  );
});
