/* 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, 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 { DiceIcon, PlusIcon, SuccessIcon, TrashIcon } from '@/icons';
import logWebUserEvent, {
  createTransactionLogger,
} from '@/logging/logWebUserEvent';
import { TagSuggestionContexts } from '@/state/createV2Store';
import {
  CREATE_VERSION,
  MAX_GPT_DESCRIPTION_PROMPT_CHARS,
} from '@/utils/constants';

import { AudioDropdown } from './AudioDropdown';
//import CreateFormContext, { CreateModes } from '../v2/CreateFormContext';
import { SuggestedStyles, SuggestedStylesVariants } from './SuggestedStyles';
import { useResizableDiv } from './useResizableDiv';

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

export const PromptInputNew = observer(
  ({
    title,
    placeholder,
    value,
    initialHeight,
    onChange,
    onClear,
    onHeightChange,
  }: Props) => {
    //const createFormContext = useContext(CreateFormContext);
    const textareaRef = useRef<any>(null);
    const { renderResizer, additionalHeight } = useResizableDiv(initialHeight);
    const { createV2 } = useStores();
    useEffect(() => {
      onHeightChange(additionalHeight);
    }, [additionalHeight]);
    return (
      <div
        className='group relative w-full rounded-[20px] bg-background-secondary'
        onClick={() => {
          textareaRef.current?.focus();
        }}
      >
        <div
          className={clsx(
            'flex hidden min-h-[56px] flex-row items-center px-4 pt-2 pl-6'
          )}
        >
          <span className='flex-1 text-base font-medium text-primary select-none'>
            {title}
          </span>
          <div>
            <Button
              variant={ButtonVariant.Standard}
              size={ButtonSize.Medium}
              shape={ButtonShape.Pill}
              icon={DiceIcon}
              aria-label='Generate random prompt suggestion'
              className='bg-transparent'
              onClick={() => {
                const newPrompt = createV2.getPromptPlaceholder();
                const newPlaceholder = createV2.getPromptPlaceholder();
                if (newPrompt) {
                  createV2.setActivePrompt(newPrompt);
                  createV2.promptPlaceholder = newPlaceholder;
                }
              }}
            />
          </div>
          <div className='flex hidden flex-row gap-2'>
            {value.length > 0 ? (
              <Button
                variant={ButtonVariant.Glass}
                shape={ButtonShape.Pill}
                size={ButtonSize.Mini}
                onClick={onClear}
                icon={TrashIcon}
              >
                Clear
              </Button>
            ) : null}
          </div>
        </div>
        <div
          className={clsx(
            'overflow-y-hidden rounded-b-2xl transition-[height] duration-500 ease-in-out'
          )}
        >
          <div
            className={`flex flex-col`}
            style={{ height: `${120 + additionalHeight}px` }}
          >
            <div className='absolute top-2 left-2 z-20'>
              {!!title ? (
                <span className='ml-4 font-medium'>{title}</span>
              ) : null}
              <Button
                variant={ButtonVariant.Standard}
                size={ButtonSize.Medium}
                shape={ButtonShape.Pill}
                icon={DiceIcon}
                aria-label='Generate random prompt suggestion'
                className='bg-transparent'
                onClick={() => {
                  const newPrompt = createV2.getPromptPlaceholder();
                  const newPlaceholder = createV2.getPromptPlaceholder();
                  if (newPrompt) {
                    createV2.setActivePrompt(newPrompt);
                    createV2.promptPlaceholder = newPlaceholder;
                  }
                  logWebUserEvent({
                    actionName: 'RefreshSuggestedPrompt',
                    context: {
                      createVersion: CREATE_VERSION,
                    },
                  });
                }}
              />
            </div>
            <Textarea
              ref={textareaRef}
              maxLength={MAX_GPT_DESCRIPTION_PROMPT_CHARS}
              isScrollable
              paddingBottom={0}
              showMaxLengthAtCharsRemaining={20}
              className='h-full w-full flex-1 resize-none rounded-2xl border-0 bg-transparent pt-[60px] pl-2 font-sans text-base outline-none'
              customHeight='h-full'
              textareaClassName='bg-transparent placeholder:brightness-150 px-4 py-0'
              onChange={(e: any) => {
                onChange?.(e.target.value);
              }}
              value={value}
              placeholder={placeholder}
              data-testid='prompt-input-textarea'
            />
          </div>
          <div className='flex h-auto flex-col'>
            <div className='flex w-full flex-row items-center px-4 pb-4'>
              <div className='flex flex-1 flex-row gap-2'>
                <AudioDropdown
                  renderTriggerButton={(callback, ref) => (
                    <Button
                      ref={ref}
                      className=''
                      iconStart={PlusIcon}
                      shape={ButtonShape.Pill}
                      onClick={callback}
                    >
                      Audio
                    </Button>
                  )}
                />
                <Button
                  className=''
                  iconStart={PlusIcon}
                  shape={ButtonShape.Pill}
                  onClick={() => {
                    // createFormContext.dispatchAction({
                    //   action: 'UPDATE_CREATE_MODE',
                    //   payload: { createMode: CreateModes.CUSTOM },
                    // });
                    createV2.setIsAdvancedMode(true);
                  }}
                >
                  Lyrics
                </Button>
              </div>
              <div className='flex flex-1 flex-row-reverse'>
                {/* <CreateV2Switch
                  label='Instrumental'
                  checked={createV2.isSimpleInstrumental}
                  onChange={(checked: boolean) => {
                    createV2.setIsSimpleInstrumental(checked);
                    logWebUserEvent({
                      actionName: 'ChangeLyricsMode',
                      context: {
                        createVersion: CREATE_VERSION,
                        createMode: 'simple',
                        lyricsModeAfter: checked ? 'instrumental' : 'auto',
                        lyricsModeBefore: checked ? 'auto' : 'instrumental',
                      },
                    });
                  }}
                /> */}
                <Button
                  iconStart={SuccessIcon}
                  shape={ButtonShape.Pill}
                  variant={
                    // createFormContext.state.isInstrumental[CreateModes.SIMPLE]
                    createV2.isSimpleInstrumental
                      ? ButtonVariant.Primary
                      : ButtonVariant.Secondary
                  }
                  onClick={() => {
                    // createFormContext.dispatchAction({
                    //   action: 'TOGGLE_INSTRUMENTAL',
                    //   payload: { createMode: CreateModes.SIMPLE },
                    // });
                    createV2.setIsSimpleInstrumental(
                      !createV2.isSimpleInstrumental
                    );
                  }}
                  iconClassName={
                    //createFormContext.state.isInstrumental[CreateModes.SIMPLE]
                    createV2.isSimpleInstrumental
                      ? 'fill-accent-pink-on-primary'
                      : 'fill-foreground-secondary'
                  }
                >
                  Instrumental
                </Button>
              </div>
            </div>
            <div className='flex flex-col border-t border-border-primary py-4 pl-4'>
              <span className='text-foreground-secondary'>Inspiration</span>
              <SuggestedStyles
                allowRefresh={false}
                icon={PlusIcon}
                isShown
                variant={SuggestedStylesVariants.OneLine}
                context={TagSuggestionContexts.SimpleTags}
                onClickStyle={(style: string) => {
                  const PROMPT_INPUT_MAX_LENGTH =
                    MAX_GPT_DESCRIPTION_PROMPT_CHARS;
                  if ((value || '').trim() === '') {
                    if (style.length <= PROMPT_INPUT_MAX_LENGTH) {
                      onChange?.(style);
                    }
                  } else {
                    const newInput = `${value}, ${style}`;
                    if (newInput.length <= PROMPT_INPUT_MAX_LENGTH) {
                      onChange?.(newInput);
                    }
                  }
                  // TODO add more relevant tags on top
                  createV2.setSuggestedTags({
                    ...createV2.suggestedTags,
                    [TagSuggestionContexts.SimpleTags]: createV2.suggestedTags[
                      TagSuggestionContexts.SimpleTags
                    ].filter((t: string) => t !== style),
                  });
                  const transactionLogger = createTransactionLogger();
                  transactionLogger.logWebUserEvent({
                    actionName: 'UseRecommendedStyle',
                    context: {
                      recommendedStyle: style,
                      styleContext: TagSuggestionContexts.SimpleTags,
                      createVersion: CREATE_VERSION,
                    },
                  });
                }}
              />
            </div>
          </div>
        </div>
        {renderResizer()}
      </div>
    );
  }
);
