import { useAuth, useClerk } from '@clerk/nextjs';
import clsx from 'clsx';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import { useRouter } from 'next/navigation';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import storageAvailable from 'storage-available';
import { twMerge } from 'tailwind-merge';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  AURA_V2_STYLE,
  ButtonShape,
  ButtonSize,
  ButtonVariant,
  DEFAULT_BUTTON_AURA_IMAGE,
} from '@/components/button/Button';
import TextareaV2, { CharCountMode } from '@/components/textarea/TextareaV2';
import { CreateIcon, SearchIcon } from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { MAX_CUSTOM_PROMPT_CHARS } from '@/utils/constants';
import { getClerkSignInRedirectProps } from '@/utils/utils';

import SunoRadioLogo from './sunoRadioLogo';

export type Props = React.HTMLAttributes<HTMLDivElement> & {
  defaultValue?: string;
  onSubmit?: (value: string) => void;
};

const RadioTopBar: React.FC<Props> = observer((props) => {
  const { className, defaultValue, onSubmit, ...restProps } = props;

  const { t } = useTranslation();
  const router = useRouter();
  const clerk = useClerk();
  const { isSignedIn } = useAuth();
  const { genForm } = useStores();

  const [value, setValue] = useState('');

  const handleSubmit = useCallback(
    (prompt: string) => {
      if (onSubmit) {
        onSubmit(prompt);
      } else {
        if (storageAvailable('localStorage') && prompt && prompt.length > 0) {
          runInAction(() => {
            genForm.hasRunSavedPrompt = false;
          });

          localStorage.setItem('prompt', prompt || '');
          localStorage.setItem('prompt_source', 'quickbox');
          localStorage.setItem('prompt_saved_at', Date.now().toString());

          logWebUserEvent({
            actionName: 'ClickedCreateOnHomepage',
            context: {
              prompt: prompt || '',
            },
          });

          if (isSignedIn) {
            router.push('/create/');
          } else {
            clerk.openSignIn({
              withSignUp: true,
              ...getClerkSignInRedirectProps('/create/'),
            });
          }
        }
      }
    },
    [router, clerk, isSignedIn, onSubmit, genForm]
  );

  const handleTextareaChange = useCallback<
    React.ChangeEventHandler<HTMLTextAreaElement>
  >((e) => {
    setValue(e.currentTarget.value);
  }, []);
  const handleTextareaKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
      if (!e.isDefaultPrevented()) {
        if (e.key === 'Enter') {
          if (!e.shiftKey) {
            // send when enter is pressed w/o shift - enables line break with shift+enter
            e.preventDefault();
            handleSubmit(value);
          } else {
            // prevent keyboard line break
            e.preventDefault();
          }
        }
      }
    },
    [value, handleSubmit]
  );
  const handleButtonClick = useCallback(() => {
    handleSubmit(value);
  }, [value, handleSubmit]);

  return (
    <div
      className={twMerge(
        'flex h-14 w-full flex-row items-center justify-between gap-4',
        'z-50',
        className
      )}
      {...restProps}
    >
      {/* Logo on the very left */}
      <div className='flex h-full shrink-0 items-end pb-2.5 pl-2.5'>
        <SunoRadioLogo fill='white' className='h-6' />
      </div>

      {/* Create input and search on the very right */}
      <div className='flex flex-row items-center gap-2'>
        <div
          className={clsx(
            'flex w-[400px] max-w-full flex-row items-center justify-center gap-1 py-1 pr-1 pl-4',
            'rounded-full bg-background-secondary text-foreground-primary placeholder:text-foreground-inactive'
          )}
        >
          <TextareaV2
            value={value}
            defaultValue={defaultValue}
            placeholder='Create your own song'
            className='rounded-none border-0 bg-transparent p-0'
            textAreaClassName={clsx(
              '-my-1 px-0 py-1 border-0',
              'h-10 leading-10',
              'whitespace-nowrap overflow-x-hidden overflow-x-auto'
            )}
            onChange={handleTextareaChange}
            onKeyDown={handleTextareaKeyDown}
            rows={1}
            maxRows={1}
            maxLength={MAX_CUSTOM_PROMPT_CHARS}
            charCountMode={CharCountMode.Never}
          />
          <Button
            iconEnd={CreateIcon}
            variant={ButtonVariant.Aura}
            size={ButtonSize.Small}
            shape={ButtonShape.Pill}
            onClick={handleButtonClick}
            disabled={!value}
            backgroundImage={DEFAULT_BUTTON_AURA_IMAGE}
            style={AURA_V2_STYLE}
          >
            {t('songActions.create')}
          </Button>
        </div>
        <div>
          <Button
            shape={ButtonShape.Pill}
            size={ButtonSize.Medium}
            icon={SearchIcon}
            aria-label={t('nav.search')}
            href='/search'
            className='bg-background-secondary p-3 text-foreground-tertiary hover:text-foreground-primary'
            iconClassName='w-5 h-5 m-0.5'
          />
        </div>
      </div>
    </div>
  );
});

export default RadioTopBar;
