import React, { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
import {
  clearAuth,
  guessUsernameFromToken,
  jwtExpSeconds,
  loadAuth,
  saveAuth,
  decodeJwtPayload,
} from "./authStorage";
import { parseAuthError } from "./authErrors";

const AuthCtx = createContext(null);

function apiBase() {
  return (import.meta?.env?.VITE_API_BASE_URL || "").replace(/\/+$/, "");
}

async function apiFetch(path, opts = {}) {
  const url = apiBase() + path;
  const res = await fetch(url, {
    credentials: "include",
    ...opts,
    headers: {
      ...(opts.headers || {}),
    },
  });
  return res;
}

function tokenEmailVerified(accessToken) {
  try {
    const p = decodeJwtPayload(accessToken);
    if (!p) return null;
    if (typeof p.email_verified === "boolean") return p.email_verified;
    if (typeof p.emailVerified === "boolean") return p.emailVerified;
    return null;
  } catch {
    return null;
  }
}

// tolerant whoami: accepts {authenticated:true} OR {username:""} OR {user:""} OR just ok+token
async function whoami(accessToken) {
  const res = await apiFetch("/api/whoami", {
    method: "GET",
    headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
  });

  const text = await res.text().catch(() => "");
  let json = null;
  try {
    json = text ? JSON.parse(text) : null;
  } catch {
    json = null;
  }

  const uname =
    (json && (json.username || json.user || json.preferred_username)) ||
    guessUsernameFromToken(accessToken) ||
    "";

  const authed =
    !!res.ok &&
    (json?.authenticated === true ||
      json?.ok === true ||
      !!json?.username ||
      !!json?.user ||
      !!uname);

  return { ok: !!res.ok, status: res.status, json, text, authenticated: authed, username: uname };
}

// NEW: /api/me is the source of truth for email_verified
async function me(accessToken) {
  const res = await apiFetch("/api/me", {
    method: "GET",
    headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
  });

  const text = await res.text().catch(() => "");
  let json = null;
  try {
    json = text ? JSON.parse(text) : null;
  } catch {
    json = null;
  }

  // Try multiple shapes
  const u = (json && (json.user || json.profile || json.me)) || json || null;

  const emailVerified =
    u && typeof u.email_verified === "boolean"
      ? u.email_verified
      : u && typeof u.emailVerified === "boolean"
      ? u.emailVerified
      : null;

  return {
    ok: !!res.ok,
    status: res.status,
    json,
    text,
    emailVerified,
  };
}

async function refreshTokens(refreshToken) {
  const res = await apiFetch("/api/refresh", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ refresh_token: refreshToken }),
  });

  const text = await res.text().catch(() => "");
  let json = null;
  try {
    json = text ? JSON.parse(text) : null;
  } catch {
    json = null;
  }

  return { ok: res.ok, status: res.status, json, text };
}

async function resendVerification(accessToken) {
  const res = await apiFetch("/api/resend-verification", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
    },
    body: JSON.stringify({}),
  });

  const text = await res.text().catch(() => "");
  let json = null;
  try {
    json = text ? JSON.parse(text) : null;
  } catch {
    json = null;
  }

  return { ok: res.ok, status: res.status, json, text };
}

function nowSec() {
  return Math.floor(Date.now() / 1000);
}

export function AuthProvider({ children }) {
  const [status, setStatus] = useState("loading"); // loading | anon | auth
  const [user, setUser] = useState(null); // { username }
  const [tokens, setTokens] = useState(null); // { access_token, refresh_token, ... }

  const [error, setError] = useState("");
  const [lastInfo, setLastInfo] = useState("");
  const [needsEmailVerification, setNeedsEmailVerification] = useState(false);

  const refreshTimer = useRef(null);

  function setAnon(msg = "") {
    setStatus("anon");
    setUser(null);
    setTokens(null);
    setError(msg || "");
    setLastInfo("");
    setNeedsEmailVerification(false);
    clearAuth();
  }

  function setAuthFromTokens(t, usernameGuess = "") {
    setTokens(t);
    saveAuth({ ...t, obtained_at: Date.now() });

    const u = usernameGuess || guessUsernameFromToken(t?.access_token) || "";
    setUser(u ? { username: u } : null);

    setStatus("auth");
    setError("");
  }

  async function refreshProfile(accessTokenOverride) {
    const at = accessTokenOverride || tokens?.access_token;
    if (!at) return { ok: false };

    // /api/me is the truth; token claim is fallback only
    const mr = await me(at);
    let verified = mr.emailVerified

    if (typeof verified !== "boolean") {
      const tv = tokenEmailVerified(at);
      if (typeof tv === "boolean") verified = tv;
    }

    if (typeof verified === "boolean") {
      setNeedsEmailVerification(!verified);
      return { ok: true, verified };
    }

    // If cannot determine, do not block UI aggressively
    setNeedsEmailVerification(false);
    return { ok: mr.ok, verified: null };
  }

  async function ensureFreshSession(existing) {
    if (!existing?.access_token) return { ok: false, reason: "no_access_token" };

    const exp = jwtExpSeconds(existing.access_token);
    const skew = 60;
    const isExpiredOrSoon = !exp || exp <= nowSec() + skew;

    if (isExpiredOrSoon) {
      if (!existing.refresh_token) return { ok: false, reason: "expired_no_refresh" };

      const rr = await refreshTokens(existing.refresh_token);
      if (!rr.ok || !rr.json?.access_token) {
        return { ok: false, reason: `refresh_failed_${rr.status}`, detail: rr.text };
      }

      const merged = { ...existing, ...rr.json };
      if (!merged.refresh_token) merged.refresh_token = existing.refresh_token;

      setAuthFromTokens(merged);
      existing = merged;
    } else {
      setAuthFromTokens(existing);
    }

    const w = await whoami(existing.access_token);
    if (w.ok && w.authenticated) {
      setUser(w.username ? { username: w.username } : null);
      setStatus("auth");
      setError("");

      // ✅ Update email verification state from backend
      await refreshProfile(existing.access_token);

      return { ok: true };
    }

    return { ok: false, reason: `whoami_${w.status}`, detail: w.text || "" };
  }

  function scheduleAutoRefresh() {
    if (refreshTimer.current) {
      clearInterval(refreshTimer.current);
      refreshTimer.current = null;
    }

    refreshTimer.current = setInterval(async () => {
      const cur = loadAuth();
      if (!cur?.access_token) return;

      const exp = jwtExpSeconds(cur.access_token);
      if (!exp) return;

      if (exp <= nowSec() + 90) {
        if (!cur.refresh_token) {
          setAnon("Session expirée (pas de refresh_token).");
          return;
        }

        const rr = await refreshTokens(cur.refresh_token);
        if (!rr.ok || !rr.json?.access_token) {
          setAnon("Session expirée. Please login again.");
          return;
        }

        const merged = { ...cur, ...rr.json };
        if (!merged.refresh_token) merged.refresh_token = cur.refresh_token;

        setAuthFromTokens(merged);

        // keep verification fresh too
        await refreshProfile(merged.access_token);
      } else {
        // lightweight: refresh verification occasionally without spamming
        // (every 30s interval already runs; but this call is only parsing token unless needed)
        const tv = tokenEmailVerified(cur.access_token);
        if (typeof tv === "boolean") setNeedsEmailVerification(!tv);
      }
    }, 30000);
  }

  async function restore() {
    setStatus("loading");
    setError("");
    setLastInfo("");
    const saved = loadAuth();
    if (!saved?.access_token) {
      setAnon("");
      return;
    }

    const r = await ensureFreshSession(saved);
    if (!r.ok) {
      setAnon("Login desynced. Please login again.");
      return;
    }

    scheduleAutoRefresh();
  }

  async function login(username, password) {
    setError("");
    setLastInfo("");
    setStatus("loading");

    const res = await apiFetch("/api/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ username, password }),
    });

    const text = await res.text().catch(() => "");
    let j = null;
    try {
      j = text ? JSON.parse(text) : null;
    } catch {
      j = null;
    }

    if (!res.ok || !j?.access_token) {
      const parsed = parseAuthError(text || "", res.status);
      setNeedsEmailVerification(parsed.code === "email_verification_required");
      setAnon(parsed.message || j?.error_description || j?.error || text || "Login failed");
      return { ok: false, status: res.status, json: j, text };
    }

    const t = { ...j, obtained_at: Date.now() };
    setAuthFromTokens(t);
    scheduleAutoRefresh();

    const w = await whoami(t.access_token);
    if (!w.ok || !w.authenticated) {
      setAnon("Login desynced. Please login again.");
      return { ok: false, status: w.status, json: w.json, text: w.text };
    }

    setUser(w.username ? { username: w.username } : null);
    setStatus("auth");

    // ✅ update verified state from backend
    await refreshProfile(t.access_token);

    return { ok: true };
  }

  function logout() {
    if (refreshTimer.current) clearInterval(refreshTimer.current);
    refreshTimer.current = null;
    setAnon("");
  }

  async function resendVerificationEmail() {
    const at = tokens?.access_token || "";
    if (!at) {
      setError("Not logged in.");
      return { ok: false };
    }

    setError("");
    setLastInfo("");

    const r = await resendVerification(at);
    if (!r.ok) {
      setError(r.json?.error || r.json?.message || r.text || `Resend failed (${r.status})`);
      return { ok: false, status: r.status };
    }

    setLastInfo("Verification email sent. Check inbox/spam, then refresh session (logout/login).");
    return { ok: true };
  }

  useEffect(() => {
    restore();
    const onStorage = (e) => {
      if (e.key === "sociowire:auth") restore();
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Backward-compatible fields expected by TopBar/MapView
  const value = useMemo(() => {
    const loading = status === "loading";
    const authenticated = status === "auth";
    const username = user?.username || "";
    const token = tokens?.access_token || "";

    return {
      // internal
      status,
      user,
      tokens,
      error,

      // expected by UI
      loading,
      authenticated,
      username,
      token,

      lastError: error || "",
      lastInfo: lastInfo || "",
      needsEmailVerification: !!needsEmailVerification,
      resendVerificationEmail,

      login,
      logout,
      restore,
      refreshProfile,
      setError,
      setLastInfo,
      setNeedsEmailVerification,
      clearError: () => setError(""),
      clearInfo: () => setLastInfo(""),
    };
  }, [status, user, tokens, error, lastInfo, needsEmailVerification]);

  return <AuthCtx.Provider value={value}>{children}</AuthCtx.Provider>;
}

export function useAuth() {
  return useContext(AuthCtx);
}
