import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { toast } from 'react-toastify';
import { useAxiosRequestProps } from 'envoc-request';
import ConfirmBaseForm, {
  ConfirmBaseFormProps,
} from '../ConfirmBaseForm/ConfirmBaseForm';
import { FormDefaults } from '../FormDefaults';

export interface ConfirmDeleteFormProps
  extends Pick<ConfirmBaseFormProps, 'style'> {
  /** Url to navigate to on success. */
  successUrl?: string;
  /** Form name (key) to apply the confirmation on. */
  form: string;
  /** Custom message to display.
   * @defaultValue `Are you sure you want to delete this?`
   */
  title?: string;
  /** Custom function when the axios request succeeds. */
  handleComplete?: Function;
  /** Custom function when the axios request fails. */
  handleError?: Function;
  /** Any components to be rendered in between the title and the buttons. */
  children?: React.ReactNode;
}

/**
 * Deletion confirmation. Navigates to a different route to allow the user to either confirm or cancel an action.
 *
 * Wraps `<ConfirmBaseForm/>`.
 */
export default function ConfirmDeleteForm({
  successUrl,
  form,
  title,
  handleComplete,
  handleError,
  children,
  ...props
}: ConfirmDeleteFormProps) {
  const navigate = useNavigate();
  const { entityId } = useParams();
  const onComplete =
    handleComplete ??
    function () {
      toast.success('Deleted!');
      goBack();
    };
  const onError =
    handleError ??
    function (error: any) {
      toast.error(
        error.response?.data?.validationFailures[0]?.errorMessage ??
          'Something went wrong talking to the portal. Contact support if this continues.'
      );
    };

  const request = {
    method: 'delete',
    url: `/api/${form}/${entityId}`,
    onComplete: onComplete,
    onError: onError,
  } as useAxiosRequestProps;

  return (
    <ConfirmBaseForm
      request={request}
      handleCancel={goBack}
      title={title ?? 'Are you sure you want to delete this?'}
      confirmButtonText="Yes"
      confirmButtonClass={
        FormDefaults.cssClassPrefix + 'confirm-delete-form-yes-button'
      }
      {...props}>
      {children}
    </ConfirmBaseForm>
  );

  function goBack() {
    if (successUrl) {
      navigate(successUrl);
    } else {
      navigate(-1);
    }
  }
}
