import React from "react";
import { formOptions, useForm } from "@tanstack/react-form";
import { app } from "@/lib/apiTreaty";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Alert, AlertTitle } from "@/components/ui/alert";
import { AlertCircle } from "lucide-react";

const PUBLIC_FRONTEND_URL = import.meta.env.PUBLIC_FRONTEND_URL as string;

export default function LoginForm() {
  const formOpts = formOptions({
    defaultValues: {
      email: "",
      contraseña: "",
    },
  });
  const form = useForm({
    ...formOpts,
    onSubmit: () => {
      // Do something with form data
      console.log("onSubmit");
      window.location.assign(PUBLIC_FRONTEND_URL + "/products");
    },
    validators: {
      onSubmitAsync: async ({ value }) => {
        // Do something with form data
        console.log("onSubmit validator");

        const { data } = await app.auth.password.post({
          email: value.email,
          password: value.contraseña,
        });
        console.log(data);

        if (data?.status != "ok") {
          return "Usuario o contraseña incorrrectos";
        }
        return undefined;
      },
    },
  });

  return (
    <>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          void form.handleSubmit();
        }}
      >
        <div className="grid w-full items-center gap-4">
          <div className="flex flex-col space-y-1.5">
            <form.Field
              name="email"
              validators={{
                onChange: ({ value }) =>
                  value.length > 0 ? null : "El email no puede estar vacío",
              }}
              children={(field) => (
                <>
                  <Label htmlFor={field.name}>Email:</Label>
                  <Input
                    name={field.name}
                    type="email"
                    placeholder="Email"
                    value={field.state.value}
                    onBlur={field.handleBlur}
                    onChange={(e) => field.handleChange(e.target.value)}
                  />
                  {field.state.meta.errors.length > 0 ? (
                    <em role="alert">{field.state.meta.errors.join(", ")}</em>
                  ) : null}
                </>
              )}
            />
          </div>
          <div className="flex flex-col space-y-1.5">
            <form.Field
              name="contraseña"
              validators={{
                onChange: ({ value }) =>
                  value.length > 0
                    ? null
                    : "La contraseña no puede estar vacía",
              }}
              children={(field) => (
                <>
                  <Label htmlFor={field.name}>Constraseña:</Label>
                  <Input
                    name={field.name}
                    type="password"
                    placeholder="Constraseña"
                    value={field.state.value}
                    onBlur={field.handleBlur}
                    onChange={(e) => field.handleChange(e.target.value)}
                  />
                  {field.state.meta.errors.length > 0 ? (
                    <em role="alert">{field.state.meta.errors.join(", ")}</em>
                  ) : null}
                </>
              )}
            />
          </div>
          <div className="flex flex-col space-y-1.5">
            <form.Subscribe
              selector={(state) => [state.errorMap]}
              children={([errorMap]) =>
                errorMap.onSubmit ? (
                  <Alert variant="destructive">
                    <AlertCircle className="h-4 w-4" />
                    <AlertTitle>Usuario o contraseña incorrrectos</AlertTitle>
                  </Alert>
                ) : null
              }
            />
            <form.Subscribe
              selector={(state) => [state.canSubmit, state.isSubmitting]}
              children={([canSubmit, isSubmitting]) => (
                <Button type="submit" disabled={!canSubmit}>
                  {isSubmitting ? "..." : "Submit"}
                </Button>
              )}
            />
          </div>
        </div>
      </form>
    </>
  );
}