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

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

      if (submitRequest.ok) {
        router.push(`/jams/content/${preset.content_id}?since=${preset.published}`);
      } 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>
  );
}