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

function LockIcon(): JSX.Element {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path
        d="M7 11V7a5 5 0 0 1 10 0v4M5 11h14a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2Z"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function ResetPasswordPage(): JSX.Element {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [password, setPassword] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const token = searchParams.get("token") ?? "";

  return (
    <AuthLayout title="Сброс пароля">
      <form
        className="z-login-form"
        onSubmit={async (event) => {
          event.preventDefault();
          setMessage("");
          setError("");
          setIsSubmitting(true);
          try {
            await resetPassword(token, password);
            setMessage("Password updated. You can log in now.");
            setTimeout(() => navigate("/login"), 1200);
          } catch (resetError) {
            setError(formatAuthError(resetError, "Password reset failed"));
          } finally {
            setIsSubmitting(false);
          }
        }}
      >
        {!token ? <AuthMessage type="error" text="Reset token is missing." /> : null}
        <AuthField
          icon={<LockIcon />}
          placeholder="New password"
          type="password"
          autoComplete="new-password"
          value={password}
          onChange={(event) => setPassword(event.target.value)}
          required
          minLength={8}
          disabled={!token}
        />
        <p className="z-login-meta">
          Password: at least 8 characters with uppercase, lowercase, and a digit.
        </p>
        <AuthSubmit loading={isSubmitting} idleText="Reset password" loadingText="Saving..." disabled={!token} />
        {message ? <AuthMessage type="success" text={message} /> : null}
        {error ? <AuthMessage type="error" text={error} /> : null}
        <p className="z-login-meta">
          <Link className="z-login-link" to="/login">
            Back to login
          </Link>
        </p>
      </form>
    </AuthLayout>
  );
}
