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 { FourStarIcon, 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;
  onGenerateLyrics: (args: { prompt?: string; e?: any }) => void;
  onGeneratePrompt: (activePrompt: string, tagString: string) => string;
  setIsEditingLyrics: (isEditing: boolean) => void;
  setHasPromptedLyrics: (hasPrompted: boolean) => void;
  value: string;
  onChange: (val: string) => void;
  disabled?: boolean;
};

export const LyricsSection = observer(
  ({
    initialHeight,
    onGenerateLyrics,
    onHeightChange,
    value,
    onChange,
    setIsEditingLyrics,
    setHasPromptedLyrics,
    disabled,
  }: 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]',
            {
              'min-h-[200px]':
                createV2.activeLyricsMode === 'custom' ||
                (createV2.activeLyricsMode === 'auto' &&
                  createV2.isAdvancedMode),
              'transition-all duration-500 ease-in-out': !isDragging,
              'h-[60px] min-h-[60px] overflow-hidden':
                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'>
              {/* <Button
                variant={ButtonVariant.Glass}
                shape={ButtonShape.Pill}
                size={ButtonSize.Mini}
                onClick={(e) => {
                  if (createV2.activeLyricsMode === 'instrumental') {
                    createV2.setActiveLyricsMode('custom');
                    createV2.setActiveLyricsModeTab('custom');
                  } else {
                    createV2.setActiveLyricsMode('instrumental');
                    createV2.setActiveLyricsModeTab('instrumental');
                  }
                  e.stopPropagation();
                }}
                iconClassName={clsx(
                  'transition-transform duration-500 ease-in-out',
                  {
                    'rotate-180': createV2.activeLyricsMode !== 'instrumental',
                  }
                )}
                icon={CaretDownIcon}
              /> */}
              {!disabled && (
                <AnimatedTabs
                  value={createV2.activeLyricsModeTab}
                  id='lyrics-tabs'
                  buttonClassName='text-sm px-3 py-2'
                  className='border-0 bg-transparent p-0 text-sm'
                  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={[
                    ...(genForm.mv === 'chirp-bluejay' &&
                    session.flags?.['mumble-mode']
                      ? [
                          {
                            value: 'mumble_mode',
                            title: 'Mumble',
                          },
                        ]
                      : []),
                    {
                      value: 'auto',
                      title: 'Auto',
                      disabled: createV2.coverExtendMode === 'cover',
                      disabledTooltip: 'Not supported for Covers',
                    },
                    // {
                    //   value: 'instrumental',
                    //   title: 'Instrumental',
                    // },
                    {
                      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',
              {
                //hidden: createV2.activeLyricsMode === 'instrumental',
                'p-0': createV2.activeLyricsMode === 'instrumental',
                'p-2 px-0 pt-2': createV2.activeLyricsMode !== 'instrumental',
                'pb-2':
                  createV2.activeLyricsMode === 'auto' &&
                  createV2.isAdvancedMode,
              }
            )}
          >
            <Textarea
              disabled={disabled}
              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',
                  'opacity-50': disabled,
                }
              )}
              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={
                createV2.activeLyricsMode === 'custom'
                  ? createV2.coverExtendMode === 'extend'
                    ? 'Add lyrics for the extended part of the song'
                    : 'Add your own lyrics here'
                  : createV2.activeLyricsMode === 'auto'
                    ? 'Describe your lyrics (Optional)'
                    : ''
              }
              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 && !disabled ? (
                <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',
            })}
          >
            {!disabled && (
              <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,
                    },
                  });
                }}
              />
            )}
            {!disabled && (
              <div
                className={clsx('flex flex-1 flex-row-reverse', {
                  hidden: createV2.activeLyricsMode === 'instrumental',
                })}
              >
                <Button
                  //disabled={createV2.activeLyricsMode !== 'custom'}
                  shape={ButtonShape.Pill}
                  size={ButtonSize.Small}
                  variant={ButtonVariant.Standard}
                  icon={FourStarIcon}
                  iconClassName='fill-strawberry-700 px-0'
                  className='bg-transparent px-2 pr-3 backdrop-blur-none'
                  onClick={() => {
                    createV2.setActiveLyricsMode('custom');
                    createV2.setActiveLyricsModeTab('custom');
                    setHasPromptedLyrics(true);
                    onGenerateLyrics({
                      prompt: '' /*onGeneratePrompt(
                      createV2.activePrompt,
                      createV2.tagInput
                    ),*/,
                    });
                    logWebUserEvent({
                      actionName: 'OpenLyricsABEditor',
                      context: {
                        createVersion: CREATE_VERSION,
                      },
                    });
                  }}
                >
                  Full Song
                </Button>
                <Button
                  //disabled={createV2.activeLyricsMode !== 'custom'}
                  shape={ButtonShape.Pill}
                  size={ButtonSize.Small}
                  variant={ButtonVariant.Standard}
                  icon={FourStarIcon}
                  iconClassName='fill-strawberry-700'
                  className='bg-transparent px-2 pr-3 backdrop-blur-none'
                  onClick={() => {
                    createV2.setActiveLyricsMode('custom');
                    createV2.setActiveLyricsModeTab('custom');
                    genForm.setLyrics(createV2.activeLyrics);
                    setIsEditingLyrics(true);
                    logWebUserEvent({
                      actionName: 'OpenLyricsCowriteEditor',
                      context: {
                        createVersion: CREATE_VERSION,
                      },
                    });
                  }}
                >
                  By Line
                </Button>
              </div>
            )}

            {/* {createV2.activeLyricsMode === 'custom' ? (
              <div className='flex-1 flex-row-reverse flex'>
                <LyricsModelSelector
                  size={ButtonSize.Small}
                  variant={ButtonVariant.Standard}
                  shape={ButtonShape.Pill}
                  value={genForm.lyricsModel}
                  onSetValue={(newValue: string) => {
                    genForm.lyricsModel = newValue;
                    lyricsABFlow.setLyricsModel(newValue);
                  }}
                />
              </div>
            ) : null} */}
          </div>
        </div>
        {/* {renderResizer()} */}
      </div>
    );
  }
);
