import { useState, type FormEvent } from "react";
import { Link, useNavigate } from "react-router";

import { client } from "@/client";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { AuthHeader, AuthPanel } from "./layout";
import {
  CaptchaField,
  FormMessage,
  PasswordInput,
  TextField,
} from "./components";
import { encryptPassword, fieldValue, getErrorMessage, passwordValue } from "./utils";

export default function RegisterPage() {
  const navigate = useNavigate();
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [publicKey, setPublicKey] = useState("");

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError("");
    setSubmitting(true);

    const form = new FormData(event.currentTarget);
    const password = passwordValue(form, "password");
    const confirmPassword = passwordValue(form, "confirmPassword");

    if (password !== confirmPassword) {
      setError("Passwords do not match.");
      setSubmitting(false);
      return;
    }

    try {
      if (!publicKey) {
        throw new Error("Captcha is not ready. Please refresh it and try again.");
      }

      await client.authRegister({
        username: fieldValue(form, "username"),
        email: fieldValue(form, "email"),
        password: encryptPassword(publicKey, password),
        captcha: fieldValue(form, "captcha"),
      });
      navigate("/auth/login");
    } catch (requestError) {
      setError(getErrorMessage(requestError));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <AuthPanel>
      <AuthHeader description="Please enter your details to sign up." title="Create account" />

      <form className="relative space-y-4 mt-10" onSubmit={(event) => void handleSubmit(event)}>
        <TextField id="username" label="Username" name="username" placeholder="Enter your username…" />
        <TextField
          id="email"
          label="E-Mail Address"
          name="email"
          placeholder="Enter your email…"
          type="email"
        />

        <div className="space-y-2">
          <Label className="text-sm font-semibold text-foreground" htmlFor="password">
            Password
          </Label>
          <PasswordInput autoComplete="new-password" id="password" name="password" placeholder="Enter your password…" />
        </div>
        <div className="space-y-2">
          <Label className="text-sm font-semibold text-foreground" htmlFor="confirmPassword">
            Confirm Password
          </Label>
          <PasswordInput autoComplete="new-password" id="confirmPassword" name="confirmPassword" placeholder="Enter your password again…" />
        </div>

        <CaptchaField onPublicKey={setPublicKey} />

        {error && <FormMessage tone="error">{error}</FormMessage>}

        <Button
          className="h-11 w-full rounded-xl text-base shadow-inner shadow-primary-foreground/10"
          disabled={submitting}
          type="submit"
        >
          {submitting ? "Please wait…" : "Sign up"}
        </Button>
      </form>

      <footer className="mt-6 text-center text-base text-muted-foreground">
        Already have an account?{" "}
        <Link className="font-semibold text-foreground transition-colors hover:text-primary" to="/auth/login">
          Sign In
        </Link>
      </footer>
    </AuthPanel>
  );
}
