import { useTheme } from '@emotion/react';
import styled from '@emotion/styled';
import { useContext } from 'react';

import Button, { ButtonShape } from '@/components/button/Button';
import {
  ContextMenuItem,
  ContextMenuTrigger,
} from '@/components/contextMenu/ContextMenu';
import { Tooltip } from '@/components/tooltip/Tooltip';
import { useContextSelector } from '@/hooks/useContextSelector';
import { MicrophoneIcon, PlusIcon, UploadIcon } from '@/icons';
import { isModelV35OrLower } from '@/utils/utils';

import UploadStateContext from '../../uploaderV2/UploadStateContext';
import CreateFormContext from '../../v2/CreateFormContext';
import { ConditionTypes, CreateFormModals } from '../../v2/types';
import { CreateTheme } from './themes';
import useFileInput from './useFileInput';

const Wrapper = styled.div<{
  hasPersonaSelected: boolean;
  hasInspoSelected: boolean;
  hasCoverSelected: boolean;
  hasTimedConditionSelected: boolean;
  isInspoDisabled: boolean;
}>`
  display: grid;
  grid-template-columns: ${(props) => {
    const hidePersona = props.hasPersonaSelected;
    const hideInspo =
      props.hasCoverSelected ||
      props.hasTimedConditionSelected ||
      props.hasInspoSelected ||
      props.isInspoDisabled;

    if (hidePersona && hideInspo) return '1fr';
    if (hidePersona || hideInspo) return '1fr 1fr';
    return '1fr 1fr 1fr';
  }};
  gap: 1px;
  width: 100%;
  height: 56px;
  border-radius: 100px;
  overflow: hidden;
`;

export const ActionShortcutsCard = ({
  onClickPersonasButton,
  onClickRecordButton,
  onClickInspoButton,
  onUploadFile,
  hasPersonaSelected = false,
  hasInspoSelected = false,
  hasCoverSelected = false,
  hasTimedConditionSelected = false,
  isInspoDisabled = false,
}: {
  onClickPersonasButton: () => void;
  onClickRecordButton: () => void;
  onClickInspoButton: () => void;
  onUploadFile: () => void;
  hasPersonaSelected?: boolean;
  hasInspoSelected?: boolean;
  hasCoverSelected?: boolean;
  hasTimedConditionSelected?: boolean;
  isInspoDisabled?: boolean;
}) => {
  const openFileInput = useFileInput({
    onFileSelect: () => {
      onUploadFile();
    },
  });
  const theme = useTheme() as CreateTheme;
  const hidePersona = hasPersonaSelected;
  const hideInspo =
    hasCoverSelected ||
    hasTimedConditionSelected ||
    hasInspoSelected ||
    isInspoDisabled;

  return (
    <Wrapper
      hasPersonaSelected={hasPersonaSelected}
      hasInspoSelected={hasInspoSelected}
      hasCoverSelected={hasCoverSelected}
      hasTimedConditionSelected={hasTimedConditionSelected}
      isInspoDisabled={isInspoDisabled}
    >
      <ContextMenuTrigger
        placement='bottom-right'
        ButtonComponent={(props) => (
          <Tooltip
            label='Upload, Record, or choose from Library'
            placement='top'
          >
            <Button
              shape={ButtonShape.Rectangle}
              iconStart={PlusIcon}
              aria-label='Add audio - upload or record'
              className={`h-full w-full bg-background-fog-thin ${theme.tailwind.bigButtonPadding} text-[14px] ${
                hidePersona && hideInspo
                  ? 'rounded-full'
                  : 'rounded-l-full rounded-r-none'
              }`}
              {...props}
            >
              Audio
            </Button>
          </Tooltip>
        )}
        ContentsComponent={({ onClose }: { onClose: () => void }) => (
          <>
            <ContextMenuItem
              onClick={() => {
                openFileInput();
                onClose();
              }}
              icon={<UploadIcon />}
            >
              Upload
            </ContextMenuItem>
            <ContextMenuItem
              onClick={() => {
                onClickRecordButton();
                onClose();
              }}
              icon={<MicrophoneIcon />}
            >
              Record
            </ContextMenuItem>
          </>
        )}
      />
      {!hidePersona && (
        <Tooltip label='Imitate a vocal or instrument' placement='top'>
          <Button
            shape={ButtonShape.Rectangle}
            iconStart={PlusIcon}
            onClick={onClickPersonasButton}
            aria-label='Add Persona'
            className={`h-full bg-background-fog-thin ${theme.tailwind.bigButtonPadding} text-[14px] ${
              hideInspo ? 'rounded-l-none rounded-r-full' : 'rounded-none'
            }`}
          >
            Persona
          </Button>
        </Tooltip>
      )}
      {!hideInspo && (
        <Tooltip label='Use songs to inspire your creation' placement='top'>
          <Button
            shape={ButtonShape.Rectangle}
            iconStart={PlusIcon}
            onClick={onClickInspoButton}
            aria-label='Add inspiration from a playlist'
            className={`h-full bg-background-fog-thin ${theme.tailwind.bigButtonPadding} rounded-l-none rounded-r-full text-[14px]`}
          >
            Inspo
          </Button>
        </Tooltip>
      )}
    </Wrapper>
  );
};

export const CreateActionShortcutsCard = () => {
  const { setIsUploadInProgress } = useContext(UploadStateContext);
  const setActiveModal = useContextSelector(
    CreateFormContext,
    (context) => context.setActiveModal
  );
  const attemptOpenPersonaModal = useContextSelector(
    CreateFormContext,
    (context) => context.attemptOpenPersonaModal
  );
  const attemptOpenInspoModal = useContextSelector(
    CreateFormContext,
    (context) => context.attemptOpenInspoModal
  );
  const hasPersonaSelected = useContextSelector(
    CreateFormContext,
    (context) => {
      const personaConditions = context.state.global.untimedConditions.persona;
      return personaConditions && personaConditions.length > 0;
    }
  );

  const hasInspoSelected = useContextSelector(CreateFormContext, (context) => {
    const playlistCondition =
      context.state.global.untimedConditions[ConditionTypes.PLAYLIST];
    const inspirationCondition =
      context.state.global.untimedConditions[ConditionTypes.INSPIRATION];
    return (
      !!playlistCondition ||
      !!(inspirationCondition && inspirationCondition.clipIds.length > 0)
    );
  });

  const hasCoverSelected = useContextSelector(CreateFormContext, (context) => {
    const coverCondition = context.state.global.untimedConditions.cover;
    return !!coverCondition;
  });

  const hasTimedConditionSelected = useContextSelector(
    CreateFormContext,
    (context) => {
      const timedCondition = context.state.global.timedCondition;
      return !!timedCondition;
    }
  );

  const currentModel = useContextSelector(
    CreateFormContext,
    (context) => context.state.global.model
  );

  const isInspoDisabled = isModelV35OrLower(currentModel);

  return (
    <ActionShortcutsCard
      onUploadFile={() => {
        setActiveModal(CreateFormModals.AudioUpload);
        setIsUploadInProgress(true);
      }}
      onClickRecordButton={() => {
        setActiveModal(CreateFormModals.AudioRecord);
        setIsUploadInProgress(true);
      }}
      onClickPersonasButton={attemptOpenPersonaModal}
      onClickInspoButton={attemptOpenInspoModal}
      hasPersonaSelected={hasPersonaSelected}
      hasInspoSelected={hasInspoSelected}
      hasCoverSelected={hasCoverSelected}
      hasTimedConditionSelected={hasTimedConditionSelected}
      isInspoDisabled={isInspoDisabled}
    />
  );
};
