"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import {
  onAuthStateChanged,
  signInWithEmailAndPassword,
  signOut,
  type User,
} from "firebase/auth";
import { doc, getDoc } from "firebase/firestore";
import { getFirebaseAuth, getDb, firebaseConfigured } from "@/lib/firebase";
import { COLLECTIONS } from "@/lib/firestore-paths";

type AuthState = {
  user: User | null;
  loading: boolean;
  isAdmin: boolean;
  signIn: (email: string, password: string) => Promise<boolean>;
  logout: () => Promise<void>;
  refreshAdmin: () => Promise<void>;
};

const AuthContext = createContext<AuthState | undefined>(undefined);

async function checkAdmin(uid: string): Promise<boolean> {
  const db = getDb();
  if (!db) return false;
  const snap = await getDoc(doc(db, COLLECTIONS.admins, uid));
  return snap.exists();
}

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);

  const refreshAdmin = useCallback(async () => {
    const auth = getFirebaseAuth();
    const u = auth?.currentUser;
    if (!u) {
      setIsAdmin(false);
      return;
    }
    const ok = await checkAdmin(u.uid);
    setIsAdmin(ok);
  }, []);

  useEffect(() => {
    if (!firebaseConfigured) {
      setLoading(false);
      return;
    }
    const auth = getFirebaseAuth();
    if (!auth) {
      setLoading(false);
      return;
    }
    const unsub = onAuthStateChanged(auth, async (u) => {
      setUser(u);
      if (u) {
        const ok = await checkAdmin(u.uid);
        setIsAdmin(ok);
      } else {
        setIsAdmin(false);
      }
      setLoading(false);
    });
    return () => unsub();
  }, []);

  const value = useMemo<AuthState>(
    () => ({
      user,
      loading,
      isAdmin,
      async signIn(email, password) {
        const auth = getFirebaseAuth();
        if (!auth) throw new Error("Firebase yapılandırılmadı.");
        const cred = await signInWithEmailAndPassword(auth, email, password);
        const ok = await checkAdmin(cred.user.uid);
        setIsAdmin(ok);
        return ok;
      },
      async logout() {
        const auth = getFirebaseAuth();
        if (auth) await signOut(auth);
        setIsAdmin(false);
      },
      refreshAdmin,
    }),
    [user, loading, isAdmin, refreshAdmin]
  );

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error("useAuth AuthProvider içinde kullanılmalıdır.");
  return ctx;
}
