import { useEffect, useState } from "preact/hooks";
import Input from "../components/form/Input.tsx";
import Button from "../components/form/Button.tsx";
import ThemeToggle from "./ThemeToggle.tsx";

interface LoginFrameProps {
  mode: "login" | "register";
}

export default function LoginFrame(props: LoginFrameProps) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [emailError, setEmailError] = useState(false);
  const [passwordError, setPasswordError] = useState(false);
  const [confirmPasswordError, setConfirmPasswordError] = useState(false);

  const checkUserLogin = async () => {
    const resp = await fetch("/api/user/login");
    const respJson = await resp.json();
    if (respJson.success) {
      // Redirect to main page if valid
      location.href = "/";
      return true;
    }
    return false;
  };

  const doUserLogin = async () => {
    const resp = await fetch("/api/user/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email,
        password,
      }),
    });
    const respJson = await resp.json();
    if (respJson.success) {
      location.href = "/";
      return true;
    }
    return false;
  };

  const doUserRegister = async () => {
    const resp = await fetch("/api/user/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email,
        password,
      }),
    });
    const respJson = await resp.json();
    if (respJson.success) {
      location.href = "/login";
      return true;
    }
    return false;
  };

  useEffect(() => {
    props.mode === "login" && checkUserLogin();
  }, []);

  const onSubmit = async () => {
    globalThis.$loading?.show();

    // Do request
    if (email && password && props.mode === "login") {
      await doUserLogin();
    } else if (
      email &&
      password &&
      confirmPassword &&
      props.mode === "register"
    ) {
      if (password !== confirmPassword) {
        setConfirmPasswordError(true);
      } else {
        await doUserRegister();
      }
    }

    // Set error
    if (!email) {
      setEmailError(true);
    }
    if (!password) {
      setPasswordError(true);
    }
    if (!confirmPassword && props.mode === "register") {
      setConfirmPasswordError(true);
    }
    globalThis.$loading?.hide();
  };

  return (
    <div className="flex items-center justify-center flex-col w-full h-full relative">
      <div className="absolute top-0 right-0">
        <ThemeToggle />
      </div>
      <h2>
        {props.mode === "register"
          ? "Register to Postdown"
          : "Sign in to Postdown"}
      </h2>
      <div className="w-[375px] mt-4 box-border p-4 text-gray-800 dark:text-gray-100 flex flex-col">
        <Input
          label="Email"
          error={emailError}
          type="text"
          placeholder="Your email"
          value={email}
          onInput={(e) => {
            setEmailError(false);
            setEmail((e.target as HTMLInputElement).value);
          }}
        />
        <Input
          label="Password"
          error={passwordError}
          type="password"
          placeholder="Your password"
          value={password}
          onInput={(e) => {
            setPasswordError(false);
            setPassword((e.target as HTMLInputElement).value);
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter") {
              onSubmit();
            }
          }}
        />
        {props.mode === "register"
          ? (
            <Input
              label="Confirm Password"
              error={confirmPasswordError}
              type="password"
              placeholder="Confirm your password"
              value={confirmPassword}
              onInput={(e) => {
                setConfirmPasswordError(false);
                setConfirmPassword((e.target as HTMLInputElement).value);
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  onSubmit();
                }
              }}
            />
          )
          : null}
        <Button
          variant="primary"
          className="h-[38px] mt-2 mb-2"
          type="button"
          onClick={onSubmit}
        >
          {props.mode === "register" ? "Register" : "Sign in"}
        </Button>
        <Button
          type="button"
          onClick={() => {
            location.href = props.mode === "register" ? "/login" : "/register";
          }}
        >
          {props.mode === "register" ? "Go Login" : "Go Register"}
        </Button>
      </div>
    </div>
  );
}
