import clsx from "clsx";
import { ReactNode } from "react";
import {
  Form,
  FormProps,
  Navigation,
  useActionData,
  useNavigation,
} from "react-router-dom";
import { FormSection } from "./section";
import { ButtonSubmit } from "./submit_button";

export interface IFormProps<IActionData extends unknown = unknown>
  extends Omit<FormProps, "children"> {
  statusSection?: null;
  submitButton?: (state: Navigation["state"]) => ReactNode;
  successElement?: (data: IActionData) => ReactNode;
  children?: ReactNode | ((state: Navigation["state"]) => ReactNode);
}

/**
 * `react-router` specific form element.
 */
export function FormRouter<IActionData extends unknown = unknown>({
  className,
  statusSection,
  submitButton,
  successElement,
  children,
  ...props
}: IFormProps<IActionData>) {
  const { state } = useNavigation();
  const actionData = useActionData() as IActionData;

  return (
    <Form className={clsx("form", className)} {...props}>
      {typeof children !== "function" ? children : children(state)}

      {statusSection !== null && (
        <FormSection>
          {state === "loading" ? (
            "Loading..."
          ) : state === "submitting" ? (
            "Submitting..."
          ) : actionData instanceof Error ? (
            <ul>
              <li>
                <pre>{String(actionData)}</pre>
              </li>
            </ul>
          ) : actionData && successElement ? (
            successElement(actionData)
          ) : (
            "Ready for submit"
          )}
        </FormSection>
      )}

      {submitButton && (
        <FormSection>
          <ButtonSubmit disabled={state !== "idle"}>
            {submitButton(state)}
          </ButtonSubmit>
        </FormSection>
      )}
    </Form>
  );
}
