import { useState } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { authClient } from "../lib/auth-client";
import { toast } from "sonner";

function ForgotPasswordPage() {
  const [email, setEmail] = useState("");
  const [isPending, setIsPending] = useState(false);

  const handleSubmit = async () => {
    setIsPending(true);
    await authClient.requestPasswordReset(
      { email, redirectTo: `${window.location.origin}/reset-password` },
      {
        onSuccess: () => {
          toast.success("Check your email for a reset link.");
          setIsPending(false);
        },
        onError: (ctx) => {
          toast.error(ctx.error.message ?? "Something went wrong.");
          setIsPending(false);
        },
      },
    );
  };

  return (
    <div className="flex flex-col items-center justify-center gap-6 p-8 max-w-sm mx-auto">
      <div className="w-full text-center">
        <h1 className="text-2xl font-black tracking-tight text-(--color-text)">
          Forgot password
        </h1>
        <p className="mt-1 text-sm text-(--color-text-muted)">
          Enter your email and we'll send you a reset link.
        </p>
      </div>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          void handleSubmit();
        }}
        className="w-full flex flex-col gap-3"
      >
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
          className="w-full rounded-2xl border border-(--color-primary-light) bg-white px-4 py-3 text-sm text-(--color-text) placeholder:text-(--color-text-muted) focus:outline-none focus:ring-2 focus:ring-(--color-primary)"
        />
        <button
          type="submit"
          disabled={isPending}
          className="w-full rounded-2xl bg-(--color-primary) px-4 py-3 text-white font-bold hover:bg-(--color-primary-dark) transition-colors disabled:opacity-50"
        >
          {isPending ? "Sending..." : "Send reset link"}
        </button>
      </form>

      <Link
        to="/"
        className="text-sm text-(--color-text-muted) hover:text-(--color-primary) transition-colors"
      >
        Back to home
      </Link>
    </div>
  );
}

export const Route = createFileRoute("/forgot-password")({
  component: ForgotPasswordPage,
});
