import { HashRouter } from 'react-router-dom';
import { Form, FormBuilderProp } from '../';
import { ValidatedApiResult } from '../Validation/ValidatedApiResult';

interface FormTestBaseProps<TForm extends object> {
  children: (formBuilder: FormBuilderProp<TForm>) => JSX.Element;
  initialValues?: TForm;
  handleSubmit?: (data: TForm | FormData) => Promise<ValidatedApiResult>;
}

export default function FormTestBase<TForm extends PersonDto>({
  children,
  initialValues,
  handleSubmit,
}: FormTestBaseProps<TForm>) {
  return (
    <HashRouter>
      <Form
        onSubmit={handleSubmit ? handleSubmit : onSubmit}
        initialValues={initialValues}>
        {children}
      </Form>
    </HashRouter>
  );

  async function onSubmit(data: TForm | FormData): Promise<ValidatedApiResult> {
    const isFormData = data instanceof FormData;
    const result = await fetch('/api/submit', {
      body: isFormData ? data : JSON.stringify(data),
      method: 'POST',
      headers: {
        'Content-Type': isFormData ? 'multipart/form-data' : 'application/json',
        'X-Show-Errors': `Errors go here`,
      },
    });

    const apiResult = await (result.json() as Promise<ValidatedApiResult>);

    if (!apiResult.hasErrors) {
      alert('submitted');
    }

    return apiResult;
  }
}

export interface PersonDto {
  name?: string | undefined;
  nameWithIcon?: string | undefined;
  numberOfArms?: number;
  phoneNumber?: string;
  yearlySalaryUSD?: number;
  isCool?: boolean;
  gradDate?: string;
  favoriteDate?: string;
  favoriteNumber?: number;
  favoriteColor?: string;
  favoriteColors?: string[];
  favoriteNames?: string[];
  createdDateTime?: string;
  allowLogin?: boolean;
  userRoles?: number[];
  profileImage?: any;
  favoritePictures?: any[];
}
