import React, { PropsWithChildren } from 'react';
import { Data } from '../../../types/data';
import { FormStation, FormStationProps } from '../FormStation';
import { ActionHandler } from '../FormStation.models';

export type CreateProps<TValues extends Data, TSubmitResponse = unknown> = Omit<
  FormStationProps<TValues, TSubmitResponse>,
  | 'actions'
  | 'onActionSelected'
  | 'alwaysShowActionsPanel'
  | 'defaultTitle'
  | 'titleProperty'
  | 'alwaysSubmitBeforeAction'
> & {
  /** The title of the station */
  title: string;

  /**
   * Called after the entity was saved.
   * The expected behavior is, to navigate the user to the details page of the created entity.
   * The function will receive the form data as well as the values returned by the `saveData` function.
   */
  onProceed: ActionHandler<TValues, TSubmitResponse>;

  /**
   * This prop allows defining a custom label for the proceed action. If it's not provided, the station will use
   * the label 'Proceed'.
   */
  proceedLabel?: string;

  /**
   * Disables the 'Proceed' button and prevents `saveData` from being called. It
   * is advised to define station message in case this is true.
   */
  denyProceeding?: boolean;
};

/**
 * This component is the basic building block for 'create' stations in the CMS.
 *
 * You can specify the form you want to show in the children prop. The form will run inside a Formik context.
 *
 * To create the form, it's usually the easiest to use Formik's `<Field/>` component and using one of the
 * `*Field` components coming from this library in the `as` prop like this:
 *
 * `<Field name="title" label="Title" as={TextField} />`
 */
export const Create = <TValues extends Data, TSubmitResponse = unknown>(
  props: PropsWithChildren<CreateProps<TValues, TSubmitResponse>>,
): JSX.Element => {
  const { onProceed, denyProceeding } = props;

  if (props.initialData.data === null) {
    // Otherwise it would show a "entity not found", which is not meaningful on a create station
    props.initialData.data = undefined;
  }

  return (
    <FormStation
      {...props}
      saveData={(values, initialData, formikHelpers) => {
        if (denyProceeding) {
          throw {
            title:
              'Unable to navigate away with pending changes still on the form.',
          };
        }
        return props.saveData(values, initialData, formikHelpers);
      }}
      defaultTitle={props.title}
      actions={[
        {
          label: props.proceedLabel ?? 'Proceed',
          onActionSelected: onProceed,
          isDisabled: denyProceeding,
        },
      ]}
      alwaysSubmitBeforeAction={true}
      showSaveHeaderAction={false}
    ></FormStation>
  );
};
