"use client";

import { useState } from "react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { authClient } from "@/lib/auth-client";
import { prepareClaim } from "./actions";

/**
 * One field, one link in an inbox.
 *
 * The address is the point: it is what the report is delivered to and what the
 * lead is, so asking for a password on top would be asking for something we do
 * not need and would then have to keep.
 *
 * `?claim=…` may carry the audits this browser ran on one of the other two
 * sites — see `prepareClaim`.
 */
export default function AuthPage() {
  const [email, setEmail] = useState("");
  const [state, setState] = useState<"idle" | "sending" | "sent" | "error">("idle");
  const [error, setError] = useState<string | null>(null);

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    setState("sending");
    setError(null);

    try {
      // Read here rather than through `useSearchParams`, which would want a
      // Suspense boundary around a value only this handler ever looks at.
      const claim = new URLSearchParams(window.location.search).get("claim");
      // Before the link is sent, so it is already waiting when it is clicked.
      await prepareClaim(email, claim);

      const { error: failure } = await authClient.signIn.magicLink({
        email,
        callbackURL: "/dashboard",
      });
      if (failure) {
        setState("error");
        setError(failure.message ?? "l'envoi a échoué");
        return;
      }
    } catch {
      setState("error");
      setError("l'envoi a échoué");
      return;
    }
    setState("sent");
  }

  return (
    <main className="mx-auto flex w-full max-w-md flex-1 flex-col justify-center px-6 py-20">
      <Card>
        <CardHeader>
          <CardTitle>Votre rapport complet</CardTitle>
          <CardDescription>
            Pas de mot de passe. Un lien à usage unique, et vos audits vous suivent.
          </CardDescription>
        </CardHeader>

        <CardContent>
          {state === "sent" ? (
            <Alert>
              <AlertDescription>
                Lien envoyé à <strong>{email}</strong>. Il est valable 15 minutes.
              </AlertDescription>
            </Alert>
          ) : (
            <form onSubmit={submit} className="flex flex-col gap-4">
              <div className="flex flex-col gap-2">
                <Label htmlFor="email">Votre email</Label>
                <Input
                  id="email"
                  type="email"
                  value={email}
                  onChange={(event) => setEmail(event.target.value)}
                  placeholder="vous@exemple.com"
                  autoComplete="email"
                  required
                  disabled={state === "sending"}
                />
              </div>

              <Button type="submit" disabled={state === "sending"}>
                {state === "sending" ? "Envoi…" : "Recevoir le lien"}
              </Button>
            </form>
          )}

          {error !== null && (
            <Alert variant="destructive" className="mt-4">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}
        </CardContent>
      </Card>
    </main>
  );
}
