import React, { useState, useCallback } from "react";
import { TextField } from "@mui/material";

type FieldProps = React.ComponentProps<typeof TextField>;
type FormEvent = React.FormEvent<HTMLFormElement>;

interface UseFormPageOptions<F> {
  defaultValue: F;
  fieldProps?: FieldProps;
  submitRequest: (value: F) => Promise<void>;
}

export function useFormPage<F extends Record<string, any>>({
  defaultValue,
  fieldProps,
  submitRequest,
}: UseFormPageOptions<F>) {
  const [loading, setLoading] = useState<boolean>(false);
  const [form, setForm] = useState<F>(defaultValue);
  const submitHandler = useCallback(
    (e: FormEvent) => {
      e.preventDefault();
      setLoading(true);
      return submitRequest(form).finally(() => {
        setLoading(false);
      });
    },
    [form]
  );

  const createFieldProps = (
    name: keyof F
  ): React.ComponentProps<typeof TextField> => {
    return {
      fullWidth: true,
      name: name as string,
      value: form[name],
      onChange: (e) => {
        setForm((state) => ({
          ...state,
          [name]: e.target.value,
        }));
      },
      ...fieldProps,
    };
  };

  return { createFieldProps, setForm, submitHandler, form, loading };
}
