import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui";
import { Button } from "@xtablo/ui/components/button";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { supabase } from "../lib/supabase";

export function ResetPasswordPage() {
  const { t } = useTranslation(["auth", "common"]);
  const [email, setEmail] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [isPending, setIsPending] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);

  const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setIsPending(true);
    setError(null);

    const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, {
      redirectTo: `${window.location.origin}/set-password`,
    });

    if (resetError) {
      setError(resetError.message);
      setIsPending(false);
      return;
    }

    setIsSubmitted(true);
    setIsPending(false);
  };

  return (
    <AuthCardShell
      title={t("auth:resetPassword.title")}
      description={t("auth:resetPassword.description")}
    >
      <div className="space-y-6">
        {error ? <AuthInfoBanner message={error} variant="error" /> : null}
        {isSubmitted ? (
          <div className="space-y-4">
            <AuthInfoBanner message="Vérifiez votre boîte mail pour continuer." variant="success" />
            <Link className="block" to="/login">
              <Button className="w-full">Retour à la connexion</Button>
            </Link>
          </div>
        ) : (
          <form className="space-y-4" onSubmit={onSubmit}>
            <div className="space-y-2">
              <Label htmlFor="email">{t("common:labels.email")}</Label>
              <Input
                id="email"
                name="email"
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                placeholder={t("auth:resetPassword.emailPlaceholder")}
                required
                disabled={isPending}
              />
            </div>

            <Button className="w-full" type="submit" disabled={isPending}>
              {t("auth:resetPassword.submit")}
            </Button>
          </form>
        )}
      </div>
    </AuthCardShell>
  );
}
