import React, { MouseEventHandler } from 'react';
import classNames from 'classnames';
import { useAxiosRequest, useAxiosRequestProps } from 'envoc-request';
import { FormDefaults } from '../FormDefaults';

// TODO: change the style prop type to Tailwind type (does this exist before Tailwind 3.1 ???), or
// should this just be type 'string'
export interface ConfirmBaseFormProps {
  /** Function to run when cancel button is clicked. */
  handleCancel?: MouseEventHandler<HTMLButtonElement>;
  /** Axios request upon confirmation */
  request: useAxiosRequestProps;
  style?: React.CSSProperties;
  /** `<h3/>` title text on top of the form. */
  title?: string;
  /** Custom confirm button text.
   * @defaultValue `Confirm`
   */
  confirmButtonText?: string;
  /** CSS class for the buttons. */
  confirmButtonClass?: string;
  /** Any components to be rendered in between the title and the buttons. */
  children?: React.ReactNode;
}

// TODO: ask about how we should use 'children'
/**
 * Confimation dialog. Navigates to a different route to allow the user to either confirm or cancel an action.
 * Commonly used for confirming delete and archive.
 *
 * See `<ConfirmDeleteForm/>` if the confirmation is specifically for deletion.
 */
export default function ConfirmBaseForm({
  handleCancel,
  request,
  style,
  title,
  confirmButtonText,
  confirmButtonClass,
  children,
  ...props
}: ConfirmBaseFormProps) {
  const webRequest = useAxiosRequest(
    Object.assign({}, request, { autoExecute: false })
  );
  const onCancel = handleCancel ?? goBack;

  return (
    <div style={{ textAlign: 'center', ...style }} {...props}>
      <h3>{title}</h3>
      {children}
      <button
        className={classNames(
          confirmButtonClass ??
            FormDefaults.cssClassPrefix + 'confirm-base-form-confirm-button'
        )}
        type="button"
        onClick={webRequest.submitRequest}>
        {confirmButtonText ?? 'Confirm'}
      </button>
      <button
        className={classNames(
          FormDefaults.cssClassPrefix + 'confirm-base-form-cancel-button'
        )}
        type="button"
        onClick={onCancel}>
        Cancel
      </button>
    </div>
  );
  function goBack() {
    window.history.back();
  }
}
