import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import { useEffect, useMemo, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import CreateFormContext from '@/app/(root)/create/v2/CreateFormContext';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import Modal from '@/components/modal/Modal';
import { useContextSelector } from '@/hooks/useContextSelector';
import { ModelType } from '@/state/sessionStore';

import { useChatMessagesStore } from '../../stores';
import { useChatContext } from '../../useChat';
import { useChatMessageActions } from '../../useChatMessageActions';
import { getUUID } from '../../utils';

type EditingModalProps = {
  onClose: () => void;
  isOpen: boolean;
};

export const EditingModal = observer(
  ({ onClose, isOpen }: EditingModalProps) => {
    const { editingContext, toolArgsCache } = useChatContext();
    const { executeGenerateSongToolCall } = useChatMessageActions();
    const setIsLoading = useChatMessagesStore((state) => state.setIsLoading);
    const forceScroll = useChatMessagesStore((state) => state.forceScroll);
    const { session } = useStores();
    const [localStyles, setLocalStyles] = useState<string>(
      editingContext?.styles ?? ''
    );
    const [localLyrics, setLocalLyrics] = useState<string>(
      editingContext?.lyrics ?? ''
    );
    const model = useContextSelector(
      CreateFormContext,
      (context) => context.state.global.model
    );
    useEffect(() => {
      setLocalStyles(editingContext?.styles ?? '');
      setLocalLyrics(editingContext?.lyrics ?? '');
    }, [editingContext]);

    const maxLengthsForModel = useMemo(() => {
      const maxLengths = session.billingModels.find(
        (m: ModelType) => m.external_key === model
      )?.max_lengths;
      const maxCustomPromptLength = maxLengths?.['prompt'];
      const maxTagsLength = maxLengths?.['tags'];
      return { styles: maxTagsLength, lyrics: maxCustomPromptLength };
    }, [model, session.billingModels]);

    if (!isOpen) {
      return null;
    }
    return (
      <Modal
        onClose={onClose}
        className='rounded-[20px]'
        contentWrapperClasses='flex flex-col items-center overflow-y-auto'
        wrapperClasses='flex flex-col h-[600px] gap-8 max-h-screen'
      >
        {editingContext.styles !== null ? (
          <div className='flex min-h-0 flex-1 flex-col gap-4'>
            <h2 className='text-lg font-medium'>Styles</h2>
            <div className='relative min-h-0 flex-1'>
              <textarea
                className='h-full w-full resize-none rounded-xl bg-background-fog-thin p-4 text-lg text-sm whitespace-pre-wrap outline-none'
                value={localStyles}
                onChange={(e) => setLocalStyles(e.target.value)}
              />
              {maxLengthsForModel.styles ? (
                <div
                  className={clsx(
                    'absolute right-2 bottom-2 z-[500] h-auto w-auto rounded-full bg-background-smoke-thick px-2 py-1 text-xs',
                    {
                      'text-accent-error':
                        localStyles.length > (maxLengthsForModel.styles ?? 0),
                      'text-foreground-secondary':
                        localStyles.length <= (maxLengthsForModel.styles ?? 0),
                    }
                  )}
                >
                  <span aria-label='Styles character limit'>
                    {localStyles.length} / {maxLengthsForModel.styles}
                  </span>
                </div>
              ) : null}
            </div>
          </div>
        ) : null}
        {editingContext.lyrics !== null ? (
          <div className='flex min-h-0 flex-1 flex-col gap-4'>
            <h2 className='text-lg font-medium'>Lyrics</h2>
            <div className='relative min-h-0 flex-1'>
              <textarea
                className='h-full w-full resize-none rounded-xl bg-background-fog-thin p-4 text-lg text-sm whitespace-pre-wrap outline-none'
                value={localLyrics}
                onChange={(e) => setLocalLyrics(e.target.value)}
              />
              {maxLengthsForModel.lyrics ? (
                <div
                  className={clsx(
                    'absolute right-2 bottom-2 z-[500] h-auto w-auto rounded-full bg-background-smoke-thick px-2 py-1 text-xs',
                    {
                      'text-accent-error':
                        localLyrics.length > (maxLengthsForModel.lyrics ?? 0),
                      'text-foreground-secondary':
                        localLyrics.length <= (maxLengthsForModel.lyrics ?? 0),
                    }
                  )}
                >
                  <span aria-label='Lyrics character limit'>
                    {localLyrics.length} / {maxLengthsForModel.lyrics}
                  </span>
                </div>
              ) : null}
            </div>
          </div>
        ) : null}
        <div className='flex w-full flex-row gap-4'>
          {editingContext.styles !== null &&
          editingContext.lyrics !== null &&
          editingContext.toolCallId ? (
            <Button
              disabled={
                (localStyles === editingContext.styles &&
                  localLyrics === editingContext.lyrics) ||
                !maxLengthsForModel.styles ||
                !maxLengthsForModel.lyrics ||
                localStyles.length > (maxLengthsForModel?.styles ?? 0) ||
                localLyrics.length > (maxLengthsForModel?.lyrics ?? 0)
              }
              className='flex-1'
              size={ButtonSize.Small}
              variant={ButtonVariant.Aura}
              shape={ButtonShape.Pill}
              onClick={async () => {
                const callId = `internal_${getUUID()}`;
                const toolArgs = toolArgsCache.get(
                  editingContext.toolCallId ?? ''
                );
                const localArgs = {
                  tags: localStyles,
                  lyrics: localLyrics,
                  title: editingContext.title,
                };
                onClose();
                forceScroll();
                setIsLoading(true);
                await executeGenerateSongToolCall({
                  callId,
                  toolArgs: { ...(toolArgs ?? {}), ...localArgs },
                  isToolEdit: true,
                });
                setIsLoading(false);
              }}
            >
              Create Song
            </Button>
          ) : // <Button
          //   disabled={
          //     (localStyles === editingContext.styles &&
          //       localLyrics === editingContext.lyrics) ||
          //     !maxLengthsForModel.styles ||
          //     !maxLengthsForModel.lyrics ||
          //     localStyles.length > (maxLengthsForModel?.styles ?? 0) ||
          //     localLyrics.length > (maxLengthsForModel?.lyrics ?? 0)
          //   }
          //   className='flex-1'
          //   size={ButtonSize.Small}
          //   variant={ButtonVariant.Aura}
          //   shape={ButtonShape.Pill}
          //   onClick={() => {}}
          // >
          //   Send to Chat
          // </Button>
          null}
        </div>
      </Modal>
    );
  }
);
