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

import { client } from "@/client";
import { Button } from "@/components/ui/button";
import { AuthHeader, AuthPanel } from "./layout";
import { FormMessage, TextField } from "./components";
import { fieldValue, getErrorMessage } from "./utils";

export default function ForgotPasswordPage() {
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

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

    const form = new FormData(event.currentTarget);

    try {
      await client.authResetPasswordRequest({
        email: fieldValue(form, "email"),
      });
      setSuccess("Password reset instructions have been sent.");
    } catch (requestError) {
      setError(getErrorMessage(requestError));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <AuthPanel>
      <AuthHeader description="Enter your email to receive a reset link." title="Forgot password" />

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

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

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

      <footer className="mt-6 text-center text-base text-muted-foreground">
        <Link className="font-semibold text-foreground transition-colors hover:text-primary" to="/auth/login">
          Back to sign in
        </Link>
      </footer>
    </AuthPanel>
  );
}
