'use client';

import { useContext, useRef, useState } from 'react';

import ConfirmationModal from '@/components/modal/publishSong/ConfirmationModal';
import ModalHeader from '@/components/modal/publishSong/ModalHeader';
import { SaveButton } from '@/components/modal/publishSong/PublishFooterButtons';
import { CancelButton } from '@/components/modal/publishSong/PublishFooterButtons';
import PublishModalFooter from '@/components/modal/publishSong/PublishModalFooter';
import TextareaV2 from '@/components/textarea/TextareaV2';
import { toast } from '@/components/toast/Toast';
import SongModalContext from '@/hooks/useSongModal';
import logWebUserEvent from '@/logging/logWebUserEvent';

export const EditLyricsScreen = ({
  editedTitle,
  currentLyrics,
  setCurrentLyrics,
  onSave,
  shouldDisableSave,
  clipId,
}: {
  onSave: () => Promise<{ success: boolean; error?: any; data?: any }>;
  editedTitle: string;
  currentLyrics: string;
  setCurrentLyrics: (lyrics: string) => void;
  shouldDisableSave: boolean;
  clipId: string;
}) => {
  const [isSaving, setIsSaving] = useState(false);
  const [isConfirmingClose, setIsConfirmingClose] = useState(false);
  const { navigateTo } = useContext(SongModalContext);
  const oldLyrics = useRef(currentLyrics);

  const handleSave = async () => {
    setIsSaving(true);
    logWebUserEvent({
      actionName: 'PublishSongModalEditLyricsSaveClicked',
      principalObjectType: 'song',
      principalObjectValue: clipId,
      context: {
        oldLyrics: oldLyrics.current,
        newLyrics: currentLyrics,
      },
    });
    const result = await onSave();
    setIsSaving(false);
    if (result.success) {
      navigateTo('main');
      toast({
        title: 'Your lyrics have been updated',
        status: 'info',
        duration: 3000,
        isClosable: true,
      });
    }
  };

  const handleCancel = () => {
    if (currentLyrics !== oldLyrics.current) {
      setIsConfirmingClose(true);
    } else {
      navigateTo('main');
    }
  };

  const handleClose = () => {
    setCurrentLyrics(oldLyrics.current);
    navigateTo('main');
  };

  return (
    <div className='flex h-full w-full flex-col justify-between'>
      <div className='flex flex-col'>
        <ModalHeader
          title={`Edit Displayed Lyrics - ${editedTitle}`}
          onBack={handleCancel}
        />
        <div className='px-6 pb-6'>
          <TextareaV2
            minRows={12}
            maxRows={14}
            maxLength={7500}
            value={currentLyrics}
            resize={true}
            onChange={(e) => setCurrentLyrics(e.target.value)}
            placeholder={'Add lyrics'}
            autoFocus
          />
        </div>
        {isConfirmingClose && (
          <ConfirmationModal
            onCancel={() => setIsConfirmingClose(false)}
            onConfirm={handleClose}
          />
        )}
      </div>

      <PublishModalFooter>
        <CancelButton onCancel={handleCancel} />
        <SaveButton
          onSave={handleSave}
          disabled={isSaving || shouldDisableSave}
          isSaving={isSaving}
          isSubmittingToContest={false}
        />
      </PublishModalFooter>
    </div>
  );
};

export default EditLyricsScreen;
