import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import { useAppContext } from "@/providers/AuthProvider";
import apiClient from "@/services/api";
import { FunctionComponent } from "preact";
import { useLocation } from "preact-iso";
import "preact/debug";
import { Controller, SubmitHandler, useForm } from "react-hook-form";
import { ILoginForm } from "./login.dto";
import classes from "./login.module.scss";

const LoginPage: FunctionComponent = () => {
  const { isLoggedIn } = useAppContext();
  const { route } = useLocation();
  const { control, handleSubmit, formState, setError } = useForm({
    defaultValues: {
      login: "",
      password: "",
    },
    mode: "onChange",
  });
  const login: SubmitHandler<ILoginForm> = async (data) => {
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const response = await apiClient<{ success: boolean; user?: any; error?: string }>(
        "/api/login/",
        {
          method: "POST",
          body: JSON.stringify({ username: data.login, password: data.password }),
          needsCsrf: true,
        },
        isLoggedIn
      );

      if (response.success) {
        isLoggedIn.value = true;
        localStorage.setItem("loggedIn", "true");
        route("/profile/tasks", true);
      } else {
        const errorMessage = response.error || "Неверный логин или пароль";
        setError("login", { message: errorMessage });
        setError("password", { message: " " });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      console.error("Login failed:", error);
      const errorMessage =
        error.message.includes("Authentication failed") || error.message.includes("Invalid credentials")
          ? "Неверный логин или пароль"
          : "Ошибка входа. Попробуйте позже.";
      setError("login", { message: errorMessage });
      setError("password", { message: " " });
    }
  };
  if (isLoggedIn.value) route("/profile/tasks", true);
  return !isLoggedIn.value ? (
    <div class={classes.login_container}>
      <div class={classes.login_card}>
        <p class={classes.login_card_name}>Антихвост</p>
        <form onSubmit={handleSubmit(login)}>
          <Controller
            name="login"
            control={control}
            rules={{
              required: "Введите логин",
            }}
            render={({ field }) => (
              <Input placeholder="Логин" textAlign="center" error={formState.errors.login?.message} {...field} />
            )}
          />
          <Controller
            name="password"
            control={control}
            rules={{
              required: "Введите пароль",
            }}
            render={({ field }) => (
              <Input
                placeholder="Пароль"
                textAlign="center"
                type="password"
                error={formState.errors.password?.message}
                {...field}
              />
            )}
          />
          <Button type="submit" color="secondary" className="w-full">
            Войти
          </Button>
        </form>
        <span class="mt-5 text-center text-xs">
          Еще нет аккаунта?{" "}
          <button
            class="cursor-pointer text-blue-500 underline"
            onClick={() => {
              route("/register", true);
            }}
          >
            Зарегистрироваться
          </button>
        </span>
      </div>
    </div>
  ) : (
    <p>Redirecting...</p>
  );
};

export default withTitle(UrlsTitle.LOGIN, LoginPage);
