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

function UserIcon(): JSX.Element {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path
        d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function ForgotPasswordPage(): JSX.Element {
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  return (
    <AuthLayout title="Восстановление пароля">
      <form
        className="z-login-form"
        onSubmit={async (event) => {
          event.preventDefault();
          setMessage("");
          setError("");
          setIsSubmitting(true);
          try {
            const data = await forgotPassword(email);
            setMessage(data.message ?? "If email is registered, reset instructions have been sent.");
          } catch (forgotError) {
            setError(formatAuthError(forgotError, "Request failed"));
          } finally {
            setIsSubmitting(false);
          }
        }}
      >
        <AuthField
          icon={<UserIcon />}
          placeholder="Email"
          type="email"
          autoComplete="email"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          required
        />
        <AuthSubmit loading={isSubmitting} loadingText="Sending..." idleText="Send reset link" />
        {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>
  );
}
