import { observer } from 'mobx-react';
import React from 'react';
import { ButtonAppearanceOptions } from '../../styles/defaults/themes.interface';
import { Button, ButtonProps } from '../Button';
import { IoSave } from 'react-icons/io5';
import { useApphouse } from '../../context/useApphouse';
import { omit } from '../../utils/obj/omit';
import { IconSizes } from '../../styles/defaults/app.token.values';
import { PromptFilename } from '../../templates/PromptFilename';
import { useLocalStyles } from '../../styles/defaults/useLocalStyles';

export interface ButtonSaveAsProps extends ButtonProps {
  /**
   * If true, the icon will not show
   * @default false
   * @optional
   */
  hideIcon?: boolean;
  /**
   * Variant of the button
   * @default 'primary'
   * @optional
   */
  variant?: ButtonAppearanceOptions;
  /**
   * The size of the icon
   * @default m
   * @optional
   */
  iconSize?: keyof typeof IconSizes;
  /**
   * The content of the button
   */
  children?: React.ReactNode;
  /**
   * The callback function that will be called when the user confirms the document name
   */
  onSave: (filename: string) => void;
  /**
   * if provided, it will substitute the icon
   * it will be ignored if hideIcon is true
   * @optional
   * @default <IoSave size={tokens.iconSize[iconSize || 'm']} />
   */
  icon?: React.ReactNode;
}

/**
 * A button that will prompt a filename before running the onClick function
 */
export const ButtonSaveAs: React.FC<ButtonSaveAsProps> = observer(
  ({
    variant = 'primary',
    children,
    hideIcon,
    title,
    iconSize,
    onSave,
    icon,
    ...rest
  }) => {
    const {
      theme: { tokens },

      closePopup,
      openPopup
    } = useApphouse();
    const localStyles = useLocalStyles(
      hideIcon || children
        ? {}
        : {
            paddingTop: 0,
            paddingBottom: 0,
            paddingLeft: 0,
            paddingRight: 0
          },
      rest.styleOverwrites
    );

    const onConfirm = (userFilename: string) => {
      onSave(userFilename);
      closePopup();
    };

    const onButtonClick = () => {
      openPopup(<PromptFilename onConfirm={onConfirm} />);
    };
    return (
      <Button
        variant={variant}
        title={title}
        onClick={onButtonClick}
        styleOverwrites={localStyles}
        {...omit(rest, ['styleOverwrites'])}
      >
        {icon && !hideIcon && icon}
        {!hideIcon && !icon && (
          <IoSave size={tokens.iconSize[iconSize || 'm']} />
        )}
        {children}
      </Button>
    );
  }
);
