import { AuthCardShell, AuthEmailPasswordForm, AuthInfoBanner } from "@xtablo/auth-ui";
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import { supabase } from "../lib/supabase";

export function LoginPage() {
  const { t } = useTranslation(["auth", "common"]);
  const { session } = useSession();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (session) {
    const redirectUrl = localStorage.getItem("clients.redirectUrl");
    if (redirectUrl) {
      localStorage.removeItem("clients.redirectUrl");
      navigate(redirectUrl);
    } else {
      navigate("/");
    }
  }

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

    const { error: signInError } = await supabase.auth.signInWithPassword({
      email,
      password,
    });

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

    const redirectUrl = localStorage.getItem("clients.redirectUrl");
    if (redirectUrl) {
      localStorage.removeItem("clients.redirectUrl");
      navigate(redirectUrl);
    } else {
      navigate("/");
    }
  };

  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}

        <AuthEmailPasswordForm
          email={email}
          password={password}
          onEmailChange={setEmail}
          onPasswordChange={setPassword}
          onSubmit={onSubmit}
          submitLabel="Connexion"
          emailLabel={t("common:labels.email")}
          passwordLabel={t("common:labels.password")}
          emailPlaceholder={t("auth:login.emailPlaceholder")}
          passwordPlaceholder={t("auth:login.passwordPlaceholder")}
          isPending={isPending}
          extraContent={
            <div className="flex items-center justify-end">
              <Link
                to="/reset-password"
                className="text-sm text-[#804EEC] transition-colors hover:text-[#6f3fd4]"
              >
                {t("auth:login.forgotPassword")}
              </Link>
            </div>
          }
        />
      </div>
    </AuthCardShell>
  );
}
