import clsx from 'clsx';
import { useState } from 'react';
import { useIsClient, useLocalStorage } from 'usehooks-ts';

import { useStores } from '@/app/(root)/AppProviders';
import { useBreakpointMd } from '@/hooks/useBreakpoint';
import { FourStarIcon } from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';

import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '../button/Button';
import LyricsEditModal from '../lyricsCowriteModal/LyricsEditModal';
import LyricsGenerateModal from '../lyricsCowriteModal/LyricsGenerateModal';
import TextareaV2, { CharCountMode } from './TextareaV2';

const LyricsCowriteTextarea = ({
  maxLyricsLength = 3000,

  lyrics,
  setLyrics,

  lyricsInputDisallowed,
  onLyricsInputInteraction,
}: {
  maxLyricsLength?: number;

  lyrics: string;
  setLyrics: (newLyrics: string) => void;

  lyricsInputDisallowed?: boolean;
  onLyricsInputInteraction?: () => void;
}) => {
  const [hasOpenedCowriteEditor, setHasOpenedCowriteEditor] = useLocalStorage(
    'has-opened-cowrite-editor-jan-27-2025-v2',
    false
  );

  const [generateActive, setGenerateActive] = useState(false);
  const [editActive, setEditActive] = useState(false);

  const { genForm } = useStores();

  const isMobile = !useBreakpointMd();
  const enableCowriteEditor = !isMobile;

  const isClient = useIsClient();

  return (
    <div
      className={clsx('relative rounded-lg bg-background-secondary', {
        'mt-3': isClient && !hasOpenedCowriteEditor,
      })}
    >
      {enableCowriteEditor && (
        <div className={'flex items-center gap-1 pl-4'}>
          <div className='grow text-sm text-foreground-secondary'>
            Write with Suno
          </div>
          <Button
            className='px-3 py-1.5'
            size={ButtonSize.Mini}
            variant={ButtonVariant.Tertiary}
            onClick={() => {
              setGenerateActive(true);
              logWebUserEvent({
                actionName: 'LyricsCowriteButtonClicked',
                context: {
                  generateInstanceToken: genForm.createSessionToken,
                },
              });
            }}
            icon={<FourStarIcon className='h-3 w-3 text-strawberry-700' />}
          >
            Full Song
          </Button>

          <Button
            className='relative px-3 py-1.5'
            size={ButtonSize.Mini}
            variant={
              !hasOpenedCowriteEditor
                ? ButtonVariant.Aura
                : ButtonVariant.Tertiary
            }
            onClick={() => {
              setEditActive(true);
              setHasOpenedCowriteEditor(true);
              logWebUserEvent({
                actionName: 'LyricsCowriteEditorButtonClicked',
                context: {
                  generateInstanceToken: genForm.createSessionToken,
                },
              });
            }}
            icon={
              <FourStarIcon
                className={clsx('h-3 w-3', {
                  ['text-strawberry-700']: hasOpenedCowriteEditor,
                  ['text-white']: !hasOpenedCowriteEditor,
                })}
              />
            }
          >
            By Line
            {!hasOpenedCowriteEditor && (
              <div className='absolute -top-[15px] -right-5 text-xs'>
                <span className='inline-block rounded-sm border bg-white px-1 text-black'>
                  New!
                </span>
              </div>
            )}
          </Button>
        </div>
      )}
      <TextareaV2
        maxLength={maxLyricsLength}
        value={lyrics}
        disabled={generateActive || editActive}
        resize
        charCountMode={CharCountMode.Always}
        onClick={() => onLyricsInputInteraction?.()}
        onKeyDown={(e) => {
          onLyricsInputInteraction?.();
          if (lyricsInputDisallowed) {
            e.preventDefault();
          }
        }}
        onChange={(e) => {
          setLyrics(e.target.value);
        }}
        placeholder={'Enter your own lyrics'}
        rows={9}
        className='pb-10'
        textAreaClassName={clsx('focus:outline-0', {
          ['blur-0']: !generateActive && !editActive,
          ['blur-[3px] pointer-events-none']: generateActive || editActive,
        })}
      />
      {!enableCowriteEditor && (
        <div className={'absolute right-3 bottom-1 left-1 p-1'}>
          <Button
            size={ButtonSize.Small}
            shape={ButtonShape.Pill}
            onClick={() => {
              setGenerateActive(true);
              logWebUserEvent({
                actionName: 'LyricsCowriteButtonClicked',
                context: {
                  generateInstanceToken: genForm.createSessionToken,
                },
              });
            }}
            icon={<FourStarIcon className='h-3 w-3 text-strawberry-700' />}
          >
            Write with Suno
          </Button>
        </div>
      )}
      <LyricsGenerateModal
        isOpen={generateActive}
        onClose={() => {
          setGenerateActive(false);
        }}
      />
      <LyricsEditModal
        isOpen={editActive}
        onClose={() => {
          setEditActive(false);
        }}
      />
    </div>
  );
};

export default LyricsCowriteTextarea;
