import { useEffect, useState, type ReactNode } from "react";

import glmLogo from "../assets/glm-logo.png";
import TaxApp from "../TaxApp";
import {
  isSupabaseConfigured,
  restoreSession,
  signInWithGoogle,
  signOut,
  verifyTaxCalendarAccess,
  type SupabaseAuthSession,
} from "../lib/supabase-auth";

type AuthState =
  | { status: "loading" }
  | { status: "signed-out"; error?: string }
  | { status: "checking"; session: SupabaseAuthSession }
  | { status: "authorized"; session: SupabaseAuthSession }
  | { status: "denied"; session: SupabaseAuthSession; error?: string }
  | { status: "configuration" };

export default function AuthGate() {
  const [state, setState] = useState<AuthState>({ status: "loading" });
  const [actionPending, setActionPending] = useState(false);

  useEffect(() => {
    let cancelled = false;

    const initialize = async () => {
      if (!isSupabaseConfigured) {
        if (!cancelled) {
          setState({ status: "configuration" });
        }
        return;
      }

      try {
        const session = await restoreSession();
        if (cancelled) return;

        if (!session) {
          setState({ status: "signed-out" });
          return;
        }

        setState({ status: "checking", session });
        const result = await verifyTaxCalendarAccess(session);
        if (cancelled) return;

        setState(
          result.allowed
            ? { status: "authorized", session: result.session }
            : { status: "denied", session: result.session },
        );
      } catch (error) {
        if (!cancelled) {
          setState({
            status: "signed-out",
            error: getErrorMessage(error),
          });
        }
      }
    };

    void initialize();
    return () => {
      cancelled = true;
    };
  }, []);

  const handleRecheck = async (session: SupabaseAuthSession) => {
    setActionPending(true);
    setState({ status: "checking", session });

    try {
      const result = await verifyTaxCalendarAccess(session);
      setState(
        result.allowed
          ? { status: "authorized", session: result.session }
          : { status: "denied", session: result.session },
      );
    } catch (error) {
      setState({
        status: "denied",
        session,
        error: getErrorMessage(error),
      });
    } finally {
      setActionPending(false);
    }
  };

  const handleLogin = async () => {
    setActionPending(true);
    try {
      await signInWithGoogle();
    } catch (error) {
      setActionPending(false);
      setState({ status: "signed-out", error: getErrorMessage(error) });
    }
  };

  const handleSignOut = async (session?: SupabaseAuthSession) => {
    setActionPending(true);
    await signOut(session);
    setActionPending(false);
    setState({ status: "signed-out" });
  };

  if (state.status === "authorized") {
    return <TaxApp session={state.session} onSignOut={() => handleSignOut(state.session)} />;
  }

  if (state.status === "loading" || state.status === "checking") {
    return <LoadingScreen checkingAccess={state.status === "checking"} />;
  }

  if (state.status === "configuration") {
    return (
      <AuthShell>
        <StatusPanel
          eyebrow="Servicio no disponible"
          title="No pudimos abrir la aplicación"
          description="La aplicación no está disponible en este momento."
          detail="Comunícate con el equipo de IT para recibir asistencia."
        />
      </AuthShell>
    );
  }

  if (state.status === "denied") {
    const verificationFailed = Boolean(state.error);
    return (
      <AuthShell>
        <StatusPanel
          eyebrow={verificationFailed ? "No se pudo validar" : "Acceso restringido"}
          title={
            verificationFailed ? "No pudimos comprobar tu acceso" : "Este correo no tiene acceso"
          }
          description={
            verificationFailed
              ? (state.error ?? "No pudimos completar la validación.")
              : "Tu cuenta no tiene acceso a esta aplicación."
          }
          detail={
            verificationFailed
              ? "Inténtalo nuevamente en unos minutos o usa otra cuenta."
              : "Comunícate con el equipo de IT si necesitas solicitar acceso."
          }
        >
          <button
            type="button"
            onClick={() => handleRecheck(state.session)}
            disabled={actionPending}
            className="w-full rounded-lg bg-glm-green px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-glm-green/90 disabled:cursor-wait disabled:opacity-60"
          >
            Volver a comprobar
          </button>
          <button
            type="button"
            onClick={() => handleSignOut(state.session)}
            disabled={actionPending}
            className="w-full rounded-lg border border-border bg-card px-4 py-2.5 text-sm font-semibold text-glm-blue transition hover:bg-muted disabled:cursor-wait disabled:opacity-60"
          >
            Usar otra cuenta
          </button>
        </StatusPanel>
      </AuthShell>
    );
  }

  return (
    <AuthShell>
      <div className="w-full max-w-md">
        <div className="mb-8">
          <p className="mb-2 text-xs font-semibold uppercase tracking-[0.18em] text-glm-green">
            Acceso interno
          </p>
          <h1 className="text-3xl font-semibold tracking-tight text-glm-blue sm:text-4xl">
            Seguimiento de Impuestos GLM
          </h1>
          <p className="mt-3 text-sm leading-6 text-muted-foreground">
            Consulta y administra el calendario tributario regional desde un solo lugar.
          </p>
        </div>

        {state.error && (
          <div className="mb-4 rounded-lg border border-destructive/25 bg-destructive/5 px-4 py-3 text-sm text-destructive">
            {state.error}
          </div>
        )}

        <button
          type="button"
          onClick={() => void handleLogin()}
          disabled={actionPending}
          className="flex w-full items-center justify-center gap-3 rounded-lg border border-border bg-card px-4 py-3 text-sm font-semibold text-foreground shadow-sm transition hover:-translate-y-px hover:border-glm-blue/35 hover:shadow-md disabled:cursor-wait disabled:opacity-60"
        >
          <GoogleIcon />
          {actionPending ? "Abriendo Google…" : "Continuar con Google"}
        </button>
      </div>
    </AuthShell>
  );
}

function AuthShell({ children }: { children: ReactNode }) {
  return (
    <main className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-5 py-10">
      <div className="pointer-events-none absolute inset-0 auth-grid opacity-55" />
      <div className="pointer-events-none absolute -left-28 top-1/4 h-72 w-72 rounded-full bg-glm-green/10 blur-3xl" />
      <div className="pointer-events-none absolute -right-24 bottom-1/4 h-80 w-80 rounded-full bg-glm-blue/10 blur-3xl" />

      <section className="relative grid w-full max-w-5xl overflow-hidden rounded-3xl border border-border bg-card shadow-[0_28px_90px_rgba(79,117,139,0.16)] lg:grid-cols-[0.9fr_1.1fr]">
        <div className="relative hidden min-h-[560px] border-r border-border bg-muted/35 p-10 lg:flex lg:flex-col lg:justify-between">
          <img src={glmLogo} alt="GomezLee Marketing" className="h-auto w-44" />

          <div>
            <div className="mb-6 h-1 w-14 rounded-full bg-glm-green" />
            <p className="max-w-xs text-2xl font-semibold leading-tight text-glm-blue">
              Obligaciones tributarias claras, organizadas y listas para dar seguimiento.
            </p>
            <p className="mt-4 max-w-sm text-sm leading-6 text-muted-foreground">
              Calendario regional de GomezLee Marketing con fechas históricas, contactos y alertas
              calculadas.
            </p>
          </div>

          <p className="text-xs text-muted-foreground">GomezLee Marketing · Uso interno</p>
        </div>

        <div className="flex min-h-[520px] items-center justify-center p-7 sm:p-12 lg:min-h-[560px] lg:p-16">
          <div className="w-full">
            <img src={glmLogo} alt="GomezLee Marketing" className="mb-10 h-auto w-36 lg:hidden" />
            {children}
          </div>
        </div>
      </section>
    </main>
  );
}

function LoadingScreen({ checkingAccess }: { checkingAccess: boolean }) {
  return (
    <main className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="text-center">
        <img src={glmLogo} alt="GomezLee Marketing" className="mx-auto h-auto w-40" />
        <div className="mx-auto mt-8 h-8 w-8 animate-spin rounded-full border-2 border-glm-blue/20 border-t-glm-green" />
        <p className="mt-4 text-sm text-muted-foreground">
          {checkingAccess ? "Verificando acceso…" : "Cargando aplicación…"}
        </p>
      </div>
    </main>
  );
}

function StatusPanel({
  eyebrow,
  title,
  description,
  detail,
  children,
}: {
  eyebrow: string;
  title: string;
  description: string;
  detail: string;
  children?: ReactNode;
}) {
  return (
    <div className="w-full max-w-md">
      <p className="mb-2 text-xs font-semibold uppercase tracking-[0.18em] text-glm-green">
        {eyebrow}
      </p>
      <h1 className="text-3xl font-semibold tracking-tight text-glm-blue">{title}</h1>
      <p className="mt-4 text-sm leading-6 text-foreground">{description}</p>
      <p className="mt-2 text-xs leading-5 text-muted-foreground">{detail}</p>
      {children && <div className="mt-7 space-y-3">{children}</div>}
    </div>
  );
}

function GoogleIcon() {
  return (
    <svg width="19" height="19" viewBox="0 0 24 24" aria-hidden="true">
      <path
        fill="#4285F4"
        d="M21.6 12.23c0-.71-.06-1.23-.2-1.78H12v3.4h5.52a4.75 4.75 0 0 1-2.05 3.03l-.02.11 2.98 2.31.21.02c1.91-1.76 2.96-4.35 2.96-7.09Z"
      />
      <path
        fill="#34A853"
        d="M12 22c2.72 0 5-.9 6.65-2.44l-3.17-2.45c-.85.59-1.99 1-3.48 1a6.04 6.04 0 0 1-5.72-4.17l-.1.01-3.1 2.4-.04.1A10.04 10.04 0 0 0 12 22Z"
      />
      <path
        fill="#FBBC05"
        d="M6.28 13.94A6.2 6.2 0 0 1 5.94 12c0-.67.12-1.32.33-1.94l-.01-.13-3.14-2.44-.1.05A10.02 10.02 0 0 0 2 12c0 1.61.38 3.13 1.04 4.46l3.24-2.52Z"
      />
      <path
        fill="#EA4335"
        d="M12 5.89c1.89 0 3.16.82 3.88 1.5l2.84-2.77C16.98 3 14.72 2 12 2a10.04 10.04 0 0 0-8.97 5.54l3.24 2.52A6.07 6.07 0 0 1 12 5.89Z"
      />
    </svg>
  );
}

function getErrorMessage(error: unknown): string {
  void error;
  return "No pudimos completar el proceso. Inténtalo nuevamente.";
}
