"use client";

import login from "@/actions/login";
import Input from "@/components/Input";
import PrettyForm from "@/components/PrettyForm";
import { LoginSchema, loginSchema } from "@/schemas";
import { Form, Formik, FormikHelpers, FormikValues } from "formik";
import React from "react";
import { toFormikValidationSchema } from "zod-formik-adapter";

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

  async function handleFormSubmit(
    data: LoginSchema,
    { setSubmitting }: FormikHelpers<LoginSchema>
  ) {
    setSubmitting(true);

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

    const res = await login(data);
    if (res.ok) {
      document.cookie = `ticket=${res.ticket}; path=/;`;
      window.location.href = "/me";
    } else {
      // only error is invalidCredentials, I am lazy
      setGlobalError("Invalid credentials.");
    }
  }

  return (
    <PrettyForm globalError={globalError}>
      <Formik
        initialValues={{ username: "", password: "" }}
        onSubmit={handleFormSubmit}
        validationSchema={toFormikValidationSchema(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>
  );
}
