import { createContext, useContext, useState, useEffect, useCallback } from "react";
import {
  onAuthStateChanged,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  signOut,
  sendEmailVerification as firebaseSendEmailVerification,
} from "firebase/auth";
import { auth } from "../firebase/config";
import { getAccount } from "../api/account";

const AuthContext = createContext(undefined);

const DEFAULT_TIER_LIMITS = {
  max_addresses: 1,
  max_alert_types: 1,
  allowed_channels: ["email"],
};

export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState(null);
  const [userTier, setUserTier] = useState("free");
  const [tierLimits, setTierLimits] = useState(DEFAULT_TIER_LIMITS);
  const [isSubscribed, setIsSubscribed] = useState(false);
  const [loading, setLoading] = useState(true);

  const fetchAccount = useCallback(async () => {
    try {
      const data = await getAccount();
      setUserTier(data.subscription_tier || "free");
      setTierLimits(data.tier_limits || DEFAULT_TIER_LIMITS);
      setIsSubscribed(
        data.subscription_status === "active" ||
          data.subscription_status === "trialing",
      );
    } catch {
      setUserTier("free");
      setTierLimits(DEFAULT_TIER_LIMITS);
      setIsSubscribed(false);
    }
  }, []);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (user) => {
      setCurrentUser(user);
      if (user) {
        await fetchAccount();
      } else {
        setUserTier("free");
        setTierLimits(DEFAULT_TIER_LIMITS);
        setIsSubscribed(false);
      }
      setLoading(false);
    });
    return unsubscribe;
  }, [fetchAccount]);

  async function signup(email, password) {
    const cred = await createUserWithEmailAndPassword(auth, email, password);
    return cred.user;
  }

  async function login(email, password) {
    const cred = await signInWithEmailAndPassword(auth, email, password);
    return cred.user;
  }

  async function logout() {
    await signOut(auth);
  }

  async function sendEmailVerification() {
    if (auth.currentUser) {
      await firebaseSendEmailVerification(auth.currentUser);
    }
  }

  async function reloadUser() {
    if (auth.currentUser) {
      await auth.currentUser.reload();
      setCurrentUser({ ...auth.currentUser });
      return auth.currentUser;
    }
    return null;
  }

  const value = {
    currentUser,
    userTier,
    tierLimits,
    isSubscribed,
    loading,
    signup,
    login,
    logout,
    sendEmailVerification,
    reloadUser,
    refreshAccount: fetchAccount,
  };

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

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}

export default useAuth;
