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 { 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 testUser = {
  login: "test",
  password: "test",
};
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) => {
    console.log(data);
    if (data.login !== testUser.login || data.password !== testUser.password) {
      setError("login", { message: "Неверный логин или пароль" });
      setError("password", { message: "Неверный логин или пароль" });
      return;
    }
    isLoggedIn.value = true;
    localStorage.setItem("loggedIn", "true");
    route("/profile/tasks", true);
  };
  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>
      </div>
    </div>
  ) : (
    <p>Redirecting...</p>
  );
};

export default withTitle(UrlsTitle.LOGIN, LoginPage);
