import { 
  signInWithEmailAndPassword, 
  createUserWithEmailAndPassword,
  signInWithPopup,
  GoogleAuthProvider,
  GithubAuthProvider,
  signOut as firebaseSignOut,
  onAuthStateChanged,
  User
} from 'firebase/auth';
import { auth } from './config';
import { createUser, getUser } from './collections';

// Providers
const googleProvider = new GoogleAuthProvider();
const githubProvider = new GithubAuthProvider();

// Sign up with email/password
export async function signUpWithEmail(email: string, password: string, displayName: string) {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    const user = userCredential.user;
    
    // Create user document in Firestore
    // Generate workspace from email or name
    const workspace = displayName.toLowerCase().replace(/\s+/g, '-') + '-account';
    
    await createUser(user.uid, {
      email: user.email!,
      displayName: displayName,
      workspace: workspace,
    });
    
    return { user, workspace };
  } catch (error: any) {
    throw new Error(error.message || 'Failed to create account');
  }
}

// Sign in with email/password
export async function signInWithEmail(email: string, password: string) {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  } catch (error: any) {
    throw new Error(error.message || 'Failed to sign in');
  }
}

// Sign in with Google
export async function signInWithGoogle() {
  try {
    const result = await signInWithPopup(auth, googleProvider);
    const user = result.user;
    
    // Check if user exists, if not create
    const existingUser = await getUser(user.uid);
    if (!existingUser) {
      const workspace = (user.displayName || user.email!.split('@')[0]).toLowerCase().replace(/\s+/g, '-') + '-account';
      await createUser(user.uid, {
        email: user.email!,
        displayName: user.displayName || undefined,
        photoURL: user.photoURL || undefined,
        workspace: workspace,
      });
    }
    
    return user;
  } catch (error: any) {
    throw new Error(error.message || 'Failed to sign in with Google');
  }
}

// Sign in with GitHub
export async function signInWithGitHub() {
  try {
    const result = await signInWithPopup(auth, githubProvider);
    const user = result.user;
    
    // Check if user exists, if not create
    const existingUser = await getUser(user.uid);
    if (!existingUser) {
      const workspace = (user.displayName || user.email!.split('@')[0]).toLowerCase().replace(/\s+/g, '-') + '-account';
      await createUser(user.uid, {
        email: user.email!,
        displayName: user.displayName || undefined,
        photoURL: user.photoURL || undefined,
        workspace: workspace,
      });
    }
    
    return user;
  } catch (error: any) {
    throw new Error(error.message || 'Failed to sign in with GitHub');
  }
}

// Sign out
export async function signOut() {
  try {
    await firebaseSignOut(auth);
  } catch (error: any) {
    throw new Error(error.message || 'Failed to sign out');
  }
}

// Listen to auth state changes
export function onAuthChange(callback: (user: User | null) => void) {
  return onAuthStateChanged(auth, callback);
}

// Get current user
export function getCurrentUser(): User | null {
  return auth.currentUser;
}

