import { customErrorMapWrapper } from "~/hooks/locale";
import { z } from "zod";
import { useZodForm } from "~/lib/zodForm";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/custom_ui/form";
import Input from "~/components/custom_ui/input";
import { useTranslation } from "~/providers/I18nProvider";
import { api } from "~/utils/api";
import toast from "react-hot-toast";
import { Button } from "~/components/ui/button";
import Link from "next/link";
import { LoadingSpinner } from "~/components/spinner";
import { useState } from "react";
import { Checkbox } from "~/components/ui/checkbox";
import { env } from "~/env.mjs";
import { useRouter } from "next/router";

export const FormLogin = () => {
  const router = useRouter();
  const { redirect } = router.query;
  const LoginSchema = z.object({
    email: z.string().email("Inserisci una email valida"),
    password: z.string(),
    checkbox: z.boolean().refine((val) => val === false), // Honeypot field
  });

  type LoginFormValues = z.infer<typeof LoginSchema>;

  const defaultValues: LoginFormValues = {
    email: "",
    password: "",
    checkbox: false, // Honeypot field
  };
  const { locale, t } = useTranslation();
  z.setErrorMap(customErrorMapWrapper(locale));

  const form = useZodForm({
    schema: LoginSchema,
    defaultValues: defaultValues,
  });

  const utils = api.useUtils();

  const { mutate, isPending } = api.auth.loginUser.useMutation({
    onSuccess: async () => {
      await utils.auth.getSession.invalidate();
      setAlreadyRequested(true);
      toast.success(t.auth.login.success);
      //await router.push(redirect ? (redirect as string) : "/");
      window.location.replace(redirect ? (redirect as string) : "/");
    },
    onError: () => {
      toast.error(t.auth.login.fail);
    },
  });
  const [altreadyRequested, setAlreadyRequested] = useState(false);
  function onSubmit(fields: LoginFormValues) {
    mutate({
      email: fields.email,
      password: fields.password,
    });
    form.reset();
  }

  return (
    <>
      <div className="text-center">
        <div className="my-8 space-y-5">
          <h3 className="text-3xl font-bold text-gray-800 sm:text-3xl">
            {t.auth.login.titolo}
          </h3>
        </div>

        {env.NEXT_PUBLIC_BASE_URL.includes("localhost") && (
          <button
            type="button"
            className="bg-yellow-300 font-semibold"
            onClick={async () => {
              form.setValue("email", "m.pedone98@gmail.com");
              form.setValue("password", "Marco1..");
              await form.handleSubmit(onSubmit)();
            }}
          >
            TEMP DEV LOGIN
          </button>
        )}

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-8 px-0.5"
            autoComplete="on"
          >
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <div className="flex flex-wrap items-center gap-x-2">
                    <FormLabel htmlFor="email">{t.auth.login.email}</FormLabel>{" "}
                    <FormMessage />
                  </div>

                  <FormControl>
                    <Input
                      placeholder="esempio@email.com"
                      {...field}
                      id="email"
                      type="email"
                      autoComplete="username"
                      required
                    />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <div className="flex flex-wrap items-center gap-x-2">
                    <FormLabel
                      htmlFor="password"
                      className="flex flex-1 justify-between"
                    >
                      <div>{t.auth.login.password}</div>
                      <Link
                        href="/auth/new-password-reset"
                        className="text-primary"
                      >
                        {t.auth.login.password_forgotten}
                      </Link>
                    </FormLabel>
                    <FormMessage />
                  </div>

                  <FormControl>
                    <Input
                      {...field}
                      id="password"
                      type="password"
                      required
                      autoComplete="current-password"
                    />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="checkbox"
              render={({ field }) => (
                <FormItem className="hidden">
                  <div className="flex flex-wrap items-center gap-x-2">
                    <FormLabel htmlFor="checkbox">Check Me</FormLabel>
                    <FormMessage />
                  </div>

                  <FormControl>
                    <Checkbox
                      id="checkbox"
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
            <Button
              disabled={isPending || altreadyRequested}
              type="submit"
              className="w-full rounded-lg bg-indigo-600 px-4 py-2 font-medium text-white duration-150 hover:bg-indigo-500 active:bg-indigo-600"
            >
              {isPending ? (
                <div className="flex items-center justify-center">
                  <LoadingSpinner size={25} />
                </div>
              ) : (
                t.auth.login.titolo
              )}
            </Button>
          </form>
        </Form>

        <br />
        <div className="px-2 pt-2 text-left text-sm text-gray-500">
          <span>{t.auth.login.psa_1}</span>
          <Link
            href="/termini-condizioni"
            className="text-indigo-600 underline hover:text-indigo-500"
          >
            {t.auth.login.psa_terms}
          </Link>
          <span>{t.auth.login.psa_2}</span>
          <Link
            href="/privacy-policy"
            className="text-indigo-600 underline hover:text-indigo-500"
          >
            {t.auth.login.psa_privacy}
          </Link>
          .
        </div>
      </div>
    </>
  );
};
