"use client";

import React, { createContext, useContext, useEffect, useState } from "react";
import { onAuthStateChanged, User as FirebaseUser, signOut } from "firebase/auth";
import { ref, get, update } from "firebase/database";
import { auth, db } from "@/lib/firebase";
import { RestaurantUser } from "@/types/user";
import { useRouter } from "next/navigation";

interface AuthContextType {
  user: RestaurantUser | null;
  firebaseUser: FirebaseUser | null;
  loading: boolean;
  logout: () => Promise<void>;
  updateRestaurantProfile: (updates: Partial<RestaurantUser>) => Promise<{ success: boolean; error?: any }>;
}

const AuthContext = createContext<AuthContextType>({
  user: null,
  firebaseUser: null,
  loading: true,
  logout: async () => {},
  updateRestaurantProfile: async () => ({ success: false }),
});

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const router = useRouter();
  const [user, setUser] = useState<RestaurantUser | null>(null);
  const [firebaseUser, setFirebaseUser] = useState<FirebaseUser | null>(null);
  const [loading, setLoading] = useState(true);

  const buildDocumentId = (email: string) => {
    return email.replace(/\./g, "_").replace(/@/g, "_at_");
  };

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
      try {
        if (currentUser && currentUser.email) {
          setFirebaseUser(currentUser);
          const docId = buildDocumentId(currentUser.email);
          const userRef = ref(db, `Restaurantes/${docId}`);
          const snapshot = await get(userRef);
          
          if (snapshot.exists()) {
            const data = snapshot.val() as RestaurantUser;
            if (data.accountType === "ESTABELECIMENTO") {
              setUser(data);
            } else {
              console.warn("User is not a restaurant");
              setUser(null);
              await signOut(auth);
            }
          } else {
            console.warn("User record not found in Restaurantes");
            setUser(null);
          }
        } else {
          setFirebaseUser(null);
          setUser(null);
        }
      } catch (error) {
        console.error("Auth initialization error:", error);
      } finally {
        setLoading(false);
      }
    });

    return () => unsubscribe();
  }, []);

  const logout = async () => {
    try {
      await signOut(auth);
      router.push("/login");
    } catch (error) {
      console.error("Erro ao fazer logout:", error);
    }
  };

  const updateRestaurantProfile = async (updates: Partial<RestaurantUser>) => {
    if (!firebaseUser?.email) return { success: false, error: "Utilizador não autenticado" };
    
    try {
      const docId = buildDocumentId(firebaseUser.email);
      const userRef = ref(db, `Restaurantes/${docId}`);
      await update(userRef, updates);
      setUser(prev => prev ? { ...prev, ...updates } : null);
      return { success: true };
    } catch (error) {
      console.error("Erro ao atualizar perfil:", error);
      return { success: false, error };
    }
  };

  return (
    <AuthContext.Provider value={{ user, firebaseUser, loading, logout, updateRestaurantProfile }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);
