"use client";

import Input from "@/components/Input";
import PrettyForm from "@/components/PrettyForm";
import { LoginFormValues, loginSchema } from "@/schemas";
import { Form, Formik, FormikHelpers, FormikValues } from "formik";
import React from "react";

export default function LoginForm() {
  const [globalError, setGlobalError] = React.useState<string | null>(null);

  async function handleFormSubmit(
    { username, password }: LoginFormValues,
    { setSubmitting }: FormikHelpers<LoginFormValues>
  ) {
    setSubmitting(true);

    if (username === "greets") {
      window.location.href = "/sekrit";
      return;
    }

    const req = await fetch("/api/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        username,
        password
      })
    });

    try {
      const res: {
        ok: boolean;
        error?: string;
        ticket: string;
      } = await req.json();

      if (res.ok) {
        document.cookie = `ticket=${res.ticket}; path=/;`;
        window.location.href = "/me";
      } else {
        // only error is invalidCredentials, I am lazy
        setGlobalError("Invalid credentials.");
      }
    } catch (err) {
      console.error(err);
      setGlobalError("shits fucked up yo");
      setSubmitting(false);
    }
  }

  return (
    <PrettyForm globalError={globalError}>
      <Formik
        initialValues={{ username: "", password: "" }}
        onSubmit={handleFormSubmit}
        validationSchema={loginSchema}
      >
        {({ isSubmitting }) => (
          <Form>
            <Input
              type="text"
              placeholder="julian"
              name="username"
              label="Username"
            />
            <Input
              type="password"
              placeholder="deeznuts47"
              name="password"
              label="Password"
            />
            <input type="submit" value="Login" disabled={isSubmitting} />
          </Form>
        )}
      </Formik>
    </PrettyForm>
  );
}
