
"use client";

import type { ReactNode } from 'react';
import { createContext, useEffect, useState } from 'react';
import type { User } from 'firebase/auth';
import { onAuthStateChanged } from 'firebase/auth';
import { auth } from '@/lib/firebase'; 
import { Spinner } from '@/components/ui/spinner';
import { fetchAndReturnTariToken } from '@/lib/actions'; 

export interface AuthContextType {
  user: User | null;
  loading: boolean;
  error: Error | null;
  tariToken: string | null; 
  tariTokenLoading: boolean; 
  tariTokenError: string | null; 
}

export const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const [tariToken, setTariToken] = useState<string | null>(null);
  const [tariTokenLoading, setTariTokenLoading] = useState<boolean>(false);
  const [tariTokenError, setTariTokenError] = useState<string | null>(null);

  useEffect(() => {
    console.log("AuthProvider: useEffect mounting. Checking auth object.");
    if (!auth) {
      console.error("AuthProvider: Firebase auth object is not available. Firebase might not have initialized correctly.");
      setLoading(false);
      setError(new Error("Firebase authentication service is not available. Please check Firebase setup and configuration."));
      return;
    }

    console.log("AuthProvider: Setting up onAuthStateChanged listener.");
    const unsubscribe = onAuthStateChanged(
      auth,
      async (currentUser) => { 
        console.log("AuthProvider: onAuthStateChanged fired. User:", currentUser);
        setUser(currentUser);
        setError(null); 
        
        if (currentUser) {
          console.log("AuthProvider: User logged in. Fetching Tari API token...");
          setTariTokenLoading(true);
          setTariToken(null); 
          setTariTokenError(null);
          try {
            const tariResult = await fetchAndReturnTariToken(); // This is a server action
            if (tariResult.token) {
              setTariToken(tariResult.token);
              console.log("AuthProvider: Tari API token fetched successfully and stored in context.");
            } else {
              setTariTokenError(tariResult.error || "Failed to fetch Tari API token (no specific error message).");
              console.error("AuthProvider: Error fetching Tari API token -", tariResult.error);
            }
          } catch (e: any) {
            setTariTokenError(e.message || "An unexpected error occurred while fetching Tari API token.");
            console.error("AuthProvider: Exception fetching Tari API token -", e);
          } finally {
            setTariTokenLoading(false);
          }
        } else {
          console.log("AuthProvider: User logged out. Clearing Tari API token from context.");
          setTariToken(null);
          setTariTokenLoading(false);
          setTariTokenError(null);
        }
        
        setLoading(false); 
      },
      (err) => {
        console.error("AuthProvider: onAuthStateChanged error:", err);
        setUser(null); 
        setError(err);
        setTariToken(null);
        setTariTokenLoading(false);
        setTariTokenError(null);
        setLoading(false);
      }
    );

    return () => {
      console.log("AuthProvider: useEffect unmounting. Unsubscribing from onAuthStateChanged.");
      unsubscribe();
    };
  }, []); 

  if (loading) { 
    return (
      <div className="flex items-center justify-center min-h-screen bg-background">
        <Spinner size="large" />
        <p className="ml-4 text-muted-foreground">Initializing authentication...</p>
      </div>
    );
  }

  return (
    <AuthContext.Provider value={{ user, loading, error, tariToken, tariTokenLoading, tariTokenError }}>
      {children}
    </AuthContext.Provider>
  );
}
