import { useCallback } from 'react';

import { useContextSelector } from '@/hooks/useContextSelector';

import CreateFormContext from '../v2/CreateFormContext';
import {
  getCurrentLyrics,
  getCurrentLyricsInputHeight,
  setCurrentLyrics,
  setCurrentLyricsInputHeight,
} from '../v2/actions/currentModeSetters';
import { LyricsSection } from './LyricsSection';

type Props = {
  lyricsABFlow: any;
  setIsEditingLyrics: (isEditing: boolean) => void;
  setHasPromptedLyrics: (hasPrompted: boolean) => void;
  setIsLyricsCowriteModalOpen: (isOpen: boolean) => void;
};

export const LyricsInputWrapper = ({
  lyricsABFlow,
  setIsEditingLyrics,
  setHasPromptedLyrics,
  setIsLyricsCowriteModalOpen,
}: Props) => {
  const lyrics = useContextSelector(
    CreateFormContext,
    (ctx) => getCurrentLyrics(ctx.state) || ''
  );
  const lyricsSectionHeight = useContextSelector(CreateFormContext, (ctx) =>
    getCurrentLyricsInputHeight(ctx.state)
  );
  const setState = useContextSelector(CreateFormContext, (ctx) => ctx.setState);
  const generatePrompt = (activePrompt: string, tagString: string) => {
    const vowels = /^[aeiouAEIOU]/;
    return `${activePrompt || ''}${!!activePrompt && !!tagString.length ? ', ' : ''}${
      tagString.length > 0
        ? `${vowels.test(tagString) ? 'an' : 'a'} ${tagString} song`
        : ''
    }`;
  };
  const generateABLyrics = useCallback(
    ({ prompt }: { e?: any; prompt?: string }) => {
      lyricsABFlow.setPrompt(prompt || '');
      setIsLyricsCowriteModalOpen(true);
    },
    []
  );
  return (
    <LyricsSection
      onGenerateLyrics={generateABLyrics}
      onGeneratePrompt={generatePrompt}
      setHasPromptedLyrics={setHasPromptedLyrics}
      setIsEditingLyrics={setIsEditingLyrics}
      initialHeight={lyricsSectionHeight}
      onHeightChange={(height: number) => {
        setState(setCurrentLyricsInputHeight(height));
      }}
      value={lyrics}
      onChange={(val: string) => {
        setState(setCurrentLyrics(val));
      }}
    />
  );
};
