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

function toIsoString(date:Date) {
  return date.getFullYear() +
      '-' + (date.getMonth() + 1).toString().padStart(2, "0") +
      '-' + (date.getDate()).toString().padStart(2, "0") +
      'T' + (date.getHours()).toString().padStart(2, "0") +
      ':' + (date.getMinutes()).toString().padStart(2, "0") +
      ':' + (date.getSeconds()).toString().padStart(2, "0");
}

export function Form({jamID, preset}:{jamID:string, preset:{
  name: string,
  description: string,
  theme: string,
  theme_description: string,
  date_start: string,
  date_end: string
}}) {
  const correctPreset = {
    ...preset,
    date_start: toIsoString(new Date(parseInt(preset.date_start))),
    date_end: toIsoString(new Date(parseInt(preset.date_end)))
  }
  const router = useRouter();
  const formik = useFormik({
    initialValues: correctPreset,
    onSubmit: async (values) => {
      const correctValues = {
        ...values,
        date_start: new Date(values.date_start).getTime(),
        date_end: new Date(values.date_end).getTime(),
      }
      const submitRequest = await fetch(`/jams/api/jams/${jamID}`, {
        method: "PATCH",
        body: JSON.stringify(correctValues)
      });

      if (submitRequest.ok) {
        router.push(`/jams/jam/${jamID}/`);
      } 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="theme">Theme</label></p>
        <input
          id="theme"
          name="theme"
          type="theme"
          onChange={formik.handleChange}
          value={formik.values.theme}
        />
        <ConditionalNull condition={formik.touched.theme != null && formik.errors.theme != null}>
          <p><small>Error: {formik.errors.theme}</small></p>
        </ConditionalNull>
      </div>
      <div>
        <p><label htmlFor="theme_description">Theme Description</label></p>
        <textarea
          id="theme_description"
          name="theme_description"
          onChange={formik.handleChange}
          value={formik.values.theme_description}
        />
        <ConditionalNull condition={formik.touched.theme_description != null && formik.errors.theme_description != null}>
          <p><small>Error: {formik.errors.theme_description}</small></p>
        </ConditionalNull>
      </div>
      <div>
        <p><label htmlFor="date_start">Date Start</label></p>
        <input
          id="date_start"
          name="date_start"
          type="datetime-local"
          onChange={formik.handleChange}
          value={formik.values.date_start}
        />
        <ConditionalNull condition={formik.touched.date_start != null && formik.errors.date_start != null}>
          <p><small>Error: {formik.errors.date_start}</small></p>
        </ConditionalNull>
      </div>
      <div>
        <p><label htmlFor="date_end">Date End</label></p>
        <input
          id="date_end"
          name="date_end"
          type="datetime-local"
          onChange={formik.handleChange}
          value={formik.values.date_end}
        />
        <ConditionalNull condition={formik.touched.date_end != null && formik.errors.date_end != null}>
          <p><small>Error: {formik.errors.date_end}</small></p>
        </ConditionalNull>
      </div>
      <br />
      <div>
        <p><label htmlFor="submit">Done?</label></p>
        <input id="submit" name="submit" type="submit" />
      </div>
     </form>
  );
}