import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { GlmLogo } from "@/components/glm-logo";
import {
  checkCotizadorAccess,
  closeUnauthorizedSession,
  consumeAccessError,
} from "@/lib/access-control";
import { getAuthRedirectUrl, getSupabaseClient } from "@/lib/supabase";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Cotizador - Walmart Connect" },
      {
        name: "description",
        content: "Acceso interno al Cotizador Walmart Connect de GomezLee Marketing.",
      },
      { property: "og:title", content: "Cotizador - Walmart Connect" },
      {
        property: "og:description",
        content: "Herramienta interna de GomezLee Marketing para Walmart Connect.",
      },
    ],
  }),
  component: LoginPage,
});

function GoogleGlyph() {
  return (
    <svg viewBox="0 0 48 48" className="size-5" aria-hidden="true">
      <path
        fill="#EA4335"
        d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.9 2.4 30.4 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.9 6.2C12.4 13.5 17.7 9.5 24 9.5z"
      />
      <path
        fill="#4285F4"
        d="M46.1 24.6c0-1.6-.1-2.8-.4-4.1H24v7.8h12.7c-.3 2.1-1.6 5.3-4.7 7.4l7.7 6c4.5-4.2 7.1-10.3 7.1-17.1z"
      />
      <path
        fill="#FBBC05"
        d="M10.5 28.6c-.5-1.5-.8-3-.8-4.6s.3-3.1.8-4.6l-7.9-6.2C1 16.3 0 20 0 24s1 7.7 2.6 10.8l7.9-6.2z"
      />
      <path
        fill="#34A853"
        d="M24 48c6.5 0 11.9-2.1 15.8-5.8l-7.7-6c-2.1 1.4-4.9 2.4-8.1 2.4-6.3 0-11.6-4-13.5-9.9l-7.9 6.2C6.5 42.6 14.6 48 24 48z"
      />
    </svg>
  );
}

function LoginPage() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [checkingSession, setCheckingSession] = useState(true);
  const [errorMessage, setErrorMessage] = useState("");

  useEffect(() => {
    let active = true;

    const verifyAccess = async () => {
      const carriedError = consumeAccessError();
      if (carriedError && active) setErrorMessage(carriedError);

      try {
        const supabase = getSupabaseClient();
        const result = await checkCotizadorAccess(supabase);
        if (!active) return;

        if (result.allowed) {
          void navigate({ to: "/chat", replace: true });
          return;
        }

        if (result.reason !== "signed_out") {
          await closeUnauthorizedSession(supabase);
          if (!active) return;
          setErrorMessage(result.message);
        }
      } catch (error) {
        console.error(error);
        if (active) {
          setErrorMessage(error instanceof Error ? error.message : "No se pudo iniciar Supabase.");
        }
      } finally {
        if (active) setCheckingSession(false);
      }
    };

    void verifyAccess();

    return () => {
      active = false;
    };
  }, [navigate]);

  const handleSignIn = async () => {
    setLoading(true);
    setErrorMessage("");

    try {
      const supabase = getSupabaseClient();
      const { error } = await supabase.auth.signInWithOAuth({
        provider: "google",
        options: {
          redirectTo: getAuthRedirectUrl(),
          queryParams: {
            access_type: "offline",
            prompt: "select_account",
            hd: "gomezleemarketing.com",
          },
        },
      });

      if (error) throw error;
    } catch (error) {
      console.error(error);
      setErrorMessage("No se pudo abrir el acceso con Google. Intenta nuevamente.");
      setLoading(false);
    }
  };

  return (
    <main className="login-canvas relative flex min-h-[100dvh] items-center justify-center overflow-hidden px-5 py-10">
      <div className="login-grid" aria-hidden="true" />
      <div className="login-orb login-orb-left" aria-hidden="true" />
      <div className="login-orb login-orb-right" aria-hidden="true" />

      <section className="animate-rise relative z-10 w-full max-w-[25rem]">
        <div className="login-card overflow-hidden rounded-[1.9rem] border border-white/80 bg-white/90 px-7 pb-9 pt-10 shadow-[var(--shadow-login)] backdrop-blur-xl sm:px-10 sm:pb-10 sm:pt-11">
          <div className="absolute inset-x-0 top-0 h-[3px] bg-[image:var(--gradient-brand)]" />

          <div className="flex flex-col items-center text-center">
            <div className="login-logo-box grid h-[5.7rem] w-[6.8rem] place-items-center rounded-[1.45rem] border border-slate-100 bg-white shadow-[0_12px_34px_-18px_rgba(79,117,139,0.55)]">
              <GlmLogo className="h-auto w-[5.2rem]" />
            </div>

            <h1 className="mt-8 text-[1.85rem] font-bold leading-tight tracking-[-0.045em] text-primary sm:text-[2rem]">
              Cotizador Walmart Connect
            </h1>

            <button
              type="button"
              onClick={handleSignIn}
              disabled={loading || checkingSession}
              className="login-google-button mt-9 inline-flex h-[3.35rem] w-full items-center justify-center gap-3 rounded-xl px-5 text-[0.94rem] font-bold text-white shadow-[0_15px_30px_-17px_rgba(79,117,139,0.9)] transition-all hover:-translate-y-0.5 hover:brightness-[1.03] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-4 disabled:pointer-events-none disabled:opacity-70"
            >
              {loading || checkingSession ? (
                <span className="size-4 animate-spin rounded-full border-2 border-white/50 border-t-white" />
              ) : (
                <GoogleGlyph />
              )}
              {checkingSession
                ? "Verificando acceso..."
                : loading
                  ? "Abriendo Google..."
                  : "Continuar con Google"}
            </button>

            {errorMessage ? (
              <p role="alert" className="mt-4 text-sm leading-relaxed text-destructive">
                {errorMessage}
              </p>
            ) : null}
          </div>
        </div>
      </section>
    </main>
  );
}
