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 { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { useClientSession, useRequestClientMagicLink } from "../hooks/useClientSession";

export function LoginPage() {
  const { t } = useTranslation(["auth", "common"]);
  const { data: client } = useClientSession();
  const requestMagicLink = useRequestClientMagicLink();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  useEffect(() => {
    if (!client) return;

    const redirectUrl = localStorage.getItem("clients.redirectUrl");
    if (redirectUrl) {
      localStorage.removeItem("clients.redirectUrl");
      navigate(redirectUrl, { replace: true });
      return;
    }

    navigate("/", { replace: true });
  }, [client, navigate]);

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

    try {
      const redirectTo = localStorage.getItem("clients.redirectUrl") || "/";
      const result = await requestMagicLink.mutateAsync({ email, redirectTo });
      setSuccessMessage(result.message);
    } catch (requestError) {
      const message = requestError instanceof Error ? requestError.message : "Connexion impossible";
      setError(message);
    }
  };

  const isPending = requestMagicLink.isPending;

  return (
    <AuthCardShell
      title={t("auth:login.title")}
      topLeft={
        <a
          href="https://www.xtablo.com"
          className="inline-flex items-center text-sm text-muted-foreground transition-colors hover:text-foreground"
        >
          <svg className="mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M15 19l-7-7 7-7"
            />
          </svg>
          {t("auth:common.backHome")}
        </a>
      }
      showThemeToggle
    >
      <div className="space-y-6">
        {error ? <AuthInfoBanner message={error} variant="error" /> : null}
        {successMessage ? <AuthInfoBanner message={successMessage} variant="success" /> : null}

        <form className="space-y-4" onSubmit={onSubmit}>
          <div className="space-y-2">
            <Label htmlFor="client-email">{t("common:labels.email")}</Label>
            <Input
              id="client-email"
              type="email"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
              placeholder={t("auth:login.emailPlaceholder")}
              autoComplete="email"
              required
            />
          </div>

          <Button type="submit" className="w-full" disabled={isPending}>
            {isPending ? "Envoi en cours..." : "Recevoir un lien de connexion"}
          </Button>
        </form>
      </div>
    </AuthCardShell>
  );
}
