import { ReactNode } from 'react';

import { Box } from '@chakra-ui/react';

import { useFormidable } from './FormidableConfig';
import { FormidableContext } from './FormidableContext';

export interface FormidableFormProps<TYPE extends object = object> {
  form: ReturnType<typeof useFormidable<TYPE>>;
  children: ReactNode;
  onSubmit?: (data: TYPE) => void;
  onSubmitDelta?: (data: Partial<TYPE>) => void;
}

export const FormidableForm = <TYPE extends object = object>({
  onSubmit,
  onSubmitDelta,
  form,
  children,
}: FormidableFormProps<TYPE>) => {
  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    const hasErrors = false; //Object.values(errors).some((err) => err);
    if (!hasErrors) {
      console.log(
        `request From submit !!! ${JSON.stringify(form.values, null, 2)}`
      );
      if (onSubmit) {
        onSubmit(form.values);
      }
      if (onSubmitDelta) {
        onSubmitDelta(form.getDeltaData(form.deltaConfig));
      }
    }
  };
  return (
    <FormidableContext form={form}>
      <Box as="form" onSubmit={handleSubmit}>
        {children}
      </Box>
    </FormidableContext>
  );
};
