'use client';
import React from "react";
import { ErrorMessage, useFormik } from "formik";
import { useRouter } from "next/navigation";
import { ConditionalNull } from "@/components/utility/Conditional";

export function Form({contentID}:{contentID:string}) {
  const router = useRouter();
  const formik = useFormik({
    initialValues: {
      content: '',
    },
    onSubmit: async (values) => {
      const submitRequest = await fetch(`/jams/api/content/${contentID}/judgements`, {
        method: "POST",
        body: JSON.stringify(values)
      });

      if (submitRequest.ok) {
        let id:string = await submitRequest.text();

        if (id == null) return;

        router.push(`/jams/content/${contentID}/`);
      } else {
        formik.setSubmitting(false);
        if (submitRequest.status == 400) {
          let errors:string[]|null = null;
          try {
            errors = await submitRequest.json();
          } catch (err) { }; // No body. Skill issue
          if (errors == null) return;
          let transformedErrors:{[key:string]:string} = {};
          errors.forEach((string) => transformedErrors[string] = "Something's wrong here");
          formik.setErrors(transformedErrors);
        } else {
          formik.setErrors({
            content: "Something went wrong..."
          });
        }
      }
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <div>
        <p><label htmlFor="content">Content</label></p>
        <textarea
          id="content"
          name="content"
          onChange={formik.handleChange}
          value={formik.values.content}
        />
        <ConditionalNull condition={formik.touched.content != null && formik.errors.content != null}>
          <p><small>Error: {formik.errors.content}</small></p>
        </ConditionalNull>
      </div>
      <div>
        <p><label htmlFor="submit">Done?</label></p>
        <input id="submit" name="submit" type="submit" />
      </div>
     </form>
  );
}