import { useState, type FormEvent } from "react";
import { Link, useNavigate, useSearchParams } 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 { FormMessage, PasswordInput, TextField } from "./components";
import { fieldValue, getErrorMessage, passwordValue } from "./utils";

export default function ResetPasswordPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

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

    const form = new FormData(event.currentTarget);

    try {
      await client.authResetPasswordVerify({
        token: fieldValue(form, "token") || searchParams.get("token") || "",
        password: passwordValue(form, "password"),
      });
      navigate("/auth/login");
    } catch (requestError) {
      setError(getErrorMessage(requestError));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <AuthPanel>
      <AuthHeader description="Choose a new password for your account." title="Reset password" />

      <form className="relative mt-6 space-y-4" onSubmit={(event) => void handleSubmit(event)}>
        {!searchParams.get("token") && (
          <TextField id="token" label="Reset Token" name="token" placeholder="Enter your reset token…" />
        )}

        <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>

        {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…" : "Reset password"}
        </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>
  );
}
