/* 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 { useEffect, 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';

const MAX_PERSONAS = 4;

const PersonaAvatar = ({
  persona,
  onRemove,
  showPlayIcon,
  playbar,
  handlePlayClip,
}: {
  persona: any;
  onRemove: () => void;
  showPlayIcon: boolean;
  playbar: any;
  handlePlayClip: (clipId: string) => void;
}) => (
  <div className='relative flex items-center'>
    <div
      className='relative h-12 w-12 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',
      }}
    >
      <ImageWithFallback
        imageSize={LARGE_IMAGE}
        className='h-full w-full object-cover'
        src={persona?.clip?.image_url || FALLBACK_IMAGE_URL}
        alt={`Persona image for ${persona?.name}`}
      />
      <div
        className='absolute inset-0 flex items-center justify-center bg-black/50 transition-opacity duration-300'
        style={{
          opacity:
            showPlayIcon ||
            (playbar.clip?.id === persona?.root_clip_id && playbar.isPlaying)
              ? 1
              : 0,
        }}
      >
        <Button
          aria-label='Play'
          icon={
            playbar.clip?.id === persona?.root_clip_id && playbar.isPlaying
              ? PauseIcon
              : PlayIcon
          }
          variant={ButtonVariant.Tertiary}
          shape={ButtonShape.Pill}
          size={ButtonSize.Small}
          onClick={(e) => {
            e.stopPropagation();
            if (persona?.root_clip_id) {
              handlePlayClip(persona.root_clip_id);
            }
          }}
        />
      </div>
    </div>
    <Link
      href={`/persona/${persona?.id}`}
      className='ml-2 line-clamp-1 font-sans text-lg font-bold font-medium whitespace-pre-wrap hover:underline'
    >
      {persona?.name}
    </Link>
    <CloseButton
      className='ml-2 bg-transparent backdrop-blur-none'
      onClick={(e) => {
        e.stopPropagation();
        onRemove();
      }}
    />
  </div>
);

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

  // Effect to update task based on number of selected personas
  useEffect(() => {
    if (createV2.activePersonas.length > 1) {
      genForm.setTask('multi_artist_consistency');
      genForm.setStyle('');
      genForm.setNegativeTags('');
      createV2.setTagInput('');
      createV2.setNegativeTagInput('');
    }
  }, [createV2.activePersonas.length]);

  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]);
    }
  };

  const handleRemovePersona = (personaId: string) => {
    createV2.removeActivePersona(personaId);
    if (createV2.activePersonas.length === 0) {
      genForm.resetPersona();
      genForm.personaId = null;
    }
  };

  const canAddMorePersonas = createV2.activePersonas.length < MAX_PERSONAS;

  return (
    <div
      className={clsx(
        'h-auto w-auto rounded-[20px] bg-background-secondary pr-4 pl-4',
        {
          'cursor-pointer py-3 hover:bg-background-tertiary':
            createV2.activePersonas.length === 0,
          'py-3': createV2.activePersonas.length > 0,
        }
      )}
      onClick={() => {
        if (createV2.activePersonas.length === 0) {
          createV2.setIsAddPopoverOpen(true);
          createV2.setAddMenuState('personas');
        }
      }}
      onMouseEnter={() => setShowPlayIcon(true)}
      onMouseLeave={() => setShowPlayIcon(false)}
    >
      <div className='flex w-full flex-col gap-2'>
        <div className='flex items-center justify-between'>
          <span className='font-sans font-medium'>
            {createV2.activePersonas.length === 0
              ? 'Personas'
              : 'Selected Personas'}
          </span>
          {canAddMorePersonas && (
            <Button
              variant={ButtonVariant.Glass}
              shape={ButtonShape.Pill}
              size={ButtonSize.Medium}
              className='bg-transparent'
              onClick={(e) => {
                e.stopPropagation();
                createV2.setIsAddPopoverOpen(true);
                createV2.setAddMenuState('personas');
              }}
              icon={PlusIcon}
            >
              {createV2.activePersonas.length === 0 ? 'Add' : null}
            </Button>
          )}
        </div>

        {createV2.activePersonas.length === 0 ? (
          <div className='flex items-center'>
            <PersonaCreateIcon className='mr-2' />
            <span className='text-sm text-foreground-tertiary'>
              Select up to {MAX_PERSONAS} Personas.
            </span>
          </div>
        ) : (
          <div className='flex flex-col gap-3'>
            {createV2.activePersonas.map((persona) => (
              <PersonaAvatar
                key={persona.id}
                persona={persona}
                onRemove={() => handleRemovePersona(persona.id)}
                showPlayIcon={showPlayIcon}
                playbar={playbar}
                handlePlayClip={handlePlayClip}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
});
