'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, JSONUserTable } from "@/lib/mastoauth/realtypes";

export function Form({userID, preset}:{userID:string, preset:JSONUserTable}) {
  const router = useRouter();
  const formik = useFormik({
    initialValues: {
      admin: preset.admin,
      banned: preset.banned,
    },
    onSubmit: async (values) => {
      console.log(values);
      const submitRequest = await fetch(`/jams/api/users/${userID}`, {
        method: "PATCH",
        body: JSON.stringify(values)
      });

      if (submitRequest.ok) {
        router.push(`/jams/user/${userID}`);
      } 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({
            admin: "Something went wrong..."
          });
        }
      }
    },
  });

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