import { useEffect, useState } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { verifyEmail } from "@modules/auth/api/authApi";
import { formatAuthError } from "@modules/auth/utils/formatAuthError";
import { AuthLayout } from "@modules/auth/components/AuthLayout";
import { AuthMessage } from "@modules/auth/components/AuthMessage";

export function VerifyPage(): JSX.Element {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [message, setMessage] = useState("Verifying your email...");
  const [error, setError] = useState("");

  useEffect(() => {
    const token = searchParams.get("token");
    if (!token) {
      setError("Verification token is missing.");
      setMessage("");
      return;
    }

    void verifyEmail(token)
      .then(() => {
        setMessage("Email verified. You can log in now.");
        setError("");
      })
      .catch((verifyError) => {
        setMessage("");
        setError(formatAuthError(verifyError, "Verification failed"));
      });
  }, [searchParams]);

  return (
    <AuthLayout title="Подтверждение email">
      <div className="z-login-form">
        {message ? <AuthMessage type="success" text={message} /> : null}
        {error ? <AuthMessage type="error" text={error} /> : null}
        <button className="z-login-submit" type="button" onClick={() => navigate("/login")}>
          Go to login
        </button>
        <p className="z-login-meta">
          <Link className="z-login-link" to="/">
            Back home
          </Link>
        </p>
      </div>
    </AuthLayout>
  );
}
