import clsx from 'clsx';
import { motion } from 'framer-motion';
import { observer } from 'mobx-react-lite';
import { ChangeEvent, useEffect, useRef } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import Textarea from '@/components/textarea/Textarea';
import { LyricsIcon, TrashIcon } from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { CREATE_VERSION } from '@/utils/constants';

import { AnimatedTabs } from './AnimatedTabs';
import { CreateV2Switch } from './CreateV2Switch';
import { useResizableDiv } from './useResizableDiv';
import { getPromptMaxLengthForModel } from './utils';

type Props = {
  initialHeight?: number;
  onHeightChange: (height: number) => void;
  value: string;
  onChange: (val: string) => void;
};

export const EditLyricsSection = observer(
  ({ initialHeight, onHeightChange, value, onChange }: Props) => {
    const { createV2, genForm, session } = useStores();
    const { renderResizer, additionalHeight, isDragging } =
      useResizableDiv(initialHeight);
    const lyricsSectionRef = useRef<any>(null);
    useEffect(() => {
      onHeightChange(additionalHeight);
    }, [additionalHeight]);
    return (
      <div
        className={clsx('relative flex flex-col', {
          'flex-1': createV2.activeLyricsMode === 'custom',
          group: createV2.activeLyricsMode !== 'instrumental',
        })}
        ref={lyricsSectionRef}
      >
        <div
          className={clsx(
            'flex flex-col rounded-[20px] bg-background-secondary p-2 backdrop-blur-[100px]',
            {
              'transition-all duration-500 ease-in-out': !isDragging,
              'h-[60px] overflow-hidden':
                createV2.activeLyricsMode === 'instrumental',
              'min-h-[200px]': createV2.activeLyricsMode !== 'instrumental',
            }
          )}
          style={{
            height:
              createV2.activeLyricsMode === 'custom' ||
              (createV2.activeLyricsMode === 'auto' && createV2.isAdvancedMode)
                ? `${280 + additionalHeight}px`
                : undefined,
          }}
        >
          <div
            className={clsx(
              'flex w-full flex-row items-center pr-2 pl-4 transition-[height,opacity] duration-500 ease-in-out',
              {
                'h-0 overflow-hidden opacity-0':
                  createV2.activeLyricsMode === 'instrumental',
                'h-[36px] opacity-100':
                  createV2.activeLyricsMode !== 'instrumental',
              }
            )}
          >
            <div className='flex flex-row items-center gap-[5px]'>
              <LyricsIcon className='h-4 w-4' />
              <span className='flex-1 text-base font-medium select-none'>
                Lyrics
              </span>
            </div>
            <div className='flex flex-1 flex-row-reverse items-center gap-2'>
              {genForm.mv === 'chirp-bluejay' &&
                session.flags?.['mumble-mode'] && (
                  <AnimatedTabs
                    value={createV2.activeLyricsModeTab}
                    id='lyrics-tabs'
                    buttonClassName='text-sm px-3 py-2'
                    className='border-0 bg-transparent p-0 text-sm'
                    disabled={createV2.activeLyricsMode === 'instrumental'}
                    onChange={(option) => {
                      const previousLyricsMode = createV2.activeLyricsMode;

                      if (option.value === 'mumble_mode') {
                        createV2.setMumbleMode(true);
                        createV2.setActiveLyricsModeTab('mumble_mode');
                        createV2.setActiveLyrics('');
                      } else {
                        createV2.setMumbleMode(false);
                        createV2.setActiveLyricsModeTab(
                          option.value as
                            | 'auto'
                            | 'custom'
                            | 'instrumental'
                            | 'mumble_mode'
                        );
                      }

                      setTimeout(() => {
                        createV2.setActiveLyricsMode(
                          option.value as
                            | 'auto'
                            | 'custom'
                            | 'instrumental'
                            | 'mumble_mode'
                        );
                        requestAnimationFrame(() => {
                          if (lyricsSectionRef.current) {
                            lyricsSectionRef.current.scrollIntoView({
                              behavior: 'smooth',
                              block: 'end',
                            });
                          }
                        });
                      }, 300);

                      logWebUserEvent({
                        actionName: 'ChangeLyricsMode',
                        context: {
                          createMode: 'custom',
                          lyricsModeAfter: option.value as
                            | 'auto'
                            | 'custom'
                            | 'instrumental'
                            | 'mumble_mode',
                          lyricsModeBefore: previousLyricsMode,
                          createVersion: CREATE_VERSION,
                        },
                      });
                    }}
                    shouldAnimate={
                      createV2.activeLyricsMode !== createV2.activeLyricsModeTab
                    }
                    options={[
                      {
                        value: 'mumble_mode',
                        title: 'Mumble',
                      },
                      {
                        value: 'custom',
                        title: 'Write Lyrics',
                      },
                    ]}
                  />
                )}
            </div>
          </div>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{
              duration: 0.3,
              scale: {
                type: 'spring',
                visualDuration: 0.4,
                bounce: 0.1,
              },
            }}
            className={clsx(
              'relative flex h-auto flex-1 flex-col overflow-hidden',
              {
                'p-0': createV2.activeLyricsMode === 'instrumental',
                'p-2 px-0 pt-2': createV2.activeLyricsMode !== 'instrumental',
              }
            )}
          >
            <Textarea
              className={clsx(
                'h-full rounded-2xl border border-foreground-primary/10 transition-all duration-200 ease-in-out',
                {
                  'max-h-0 opacity-0':
                    createV2.activeLyricsMode === 'instrumental' ||
                    createV2.activeLyricsMode === 'mumble_mode',
                  'max-h-[2000px] opacity-100':
                    createV2.activeLyricsMode !== 'instrumental' &&
                    createV2.activeLyricsMode !== 'mumble_mode',
                }
              )}
              textareaClassName='placeholder:brightness-150 h-full'
              bgColor='transparent'
              isReadOnly={
                createV2.activeLyricsMode === 'instrumental' ||
                createV2.activeLyricsMode === 'mumble_mode'
              }
              showMaxLengthAtCharsRemaining={
                createV2.activeLyricsMode === 'custom' ? 200 : 20
              }
              paddingBottom={0}
              maxLength={
                createV2.activeLyricsMode === 'custom'
                  ? getPromptMaxLengthForModel(genForm.mv)
                  : 200
              }
              isScrollable
              placeholder={'Add your own lyrics here'}
              value={value}
              onChange={function (
                event: ChangeEvent<HTMLTextAreaElement>
              ): void {
                onChange(event.target.value);
              }}
              data-testid='lyrics-input-textarea'
            />
            <div className='absolute right-1 bottom-4'>
              {createV2.activeLyrics.length > 0 ? (
                <Button
                  variant={ButtonVariant.Secondary}
                  shape={ButtonShape.Pill}
                  size={ButtonSize.Mini}
                  className='mr-2'
                  onClick={(e) => {
                    createV2.setActiveLyrics('');
                    logWebUserEvent({
                      actionName: 'ClearLyrics',
                      context: {
                        createVersion: CREATE_VERSION,
                      },
                    });
                    e.stopPropagation();
                  }}
                  icon={TrashIcon}
                />
              ) : null}
            </div>
            <div className='absolute right-0 bottom-0 -mr-[7px]'>
              {renderResizer()}
            </div>
          </motion.div>
          <div
            className={clsx('flex flex-row items-center gap-2 px-2', {
              'pt-[6px] pb-[6px]': createV2.activeLyricsMode === 'instrumental',
              'pt-0': createV2.activeLyricsMode !== 'instrumental',
            })}
          >
            <CreateV2Switch
              label='Instrumental'
              checked={createV2.activeLyricsMode === 'instrumental'}
              onChange={(checked: boolean) => {
                const previousLyricsMode = createV2.activeLyricsMode;
                if (checked) {
                  createV2.setActiveLyricsMode('instrumental');
                  createV2.setActiveLyricsModeTab('instrumental');
                } else {
                  createV2.setActiveLyricsMode('custom');
                  createV2.setActiveLyricsModeTab('custom');
                }
                logWebUserEvent({
                  actionName: 'ChangeLyricsMode',
                  context: {
                    createMode: 'custom',
                    lyricsModeAfter: checked ? 'instrumental' : 'custom',
                    lyricsModeBefore: previousLyricsMode,
                    createVersion: CREATE_VERSION,
                  },
                });
              }}
            />
          </div>
        </div>
      </div>
    );
  }
);
