'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({jamID}:{jamID:string}) {
  const router = useRouter();
  const formik = useFormik({
    initialValues: {
      name: '',
      description: '',
      url: '',
    },
    onSubmit: async (values) => {
      const submitRequest = await fetch(`/jams/api/jams/${jamID}/content`, {
        method: "POST",
        body: JSON.stringify(values)
      });

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

        if (id == null) return;

        router.push(`/jams/content/${id}/`);
      } 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({
            name: "Something went wrong..."
          });
        }
      }
    },
  });

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