import React, { useRef, useState } from 'react';
import './App.css';

/*
import firebase from 'firebase/';
import 'firebase/firestore';
import 'firebase/auth';
*/
import firebase from 'firebase/compat/app'; 

import 'firebase/compat/firestore';

import 'firebase/compat/auth'; 

import {useAuthState} from 'react-firebase-hooks/auth';
import {useCollectionData} from 'react-firebase-hooks/firestore';

firebase.initializeApp({
  apiKey: "AIzaSyDhXnMyDGw3ei7-4M-x1LXcEZvATPx0tbc",
  authDomain: "yapper-204ab.firebaseapp.com",
  projectId: "yapper-204ab",
  storageBucket: "yapper-204ab.firebasestorage.app",
  messagingSenderId: "31767433105",
  appId: "1:31767433105:web:b75ea782115bc2fe8a1430",
  measurementId: "G-ERFF6SL9W6"
});

const auth = firebase.auth();
const firestore  =firebase.firestore();



function App() {
  const [user] = useAuthState(auth);

  return (
    <div className="App">
      <header className="App-header">
        
      </header>

      <section>
        {user ? <ChatRoom/> : <SignIn/>}
      </section>
    </div>
  );
}

function SignIn(){
  const signInWithGoogle = () =>{
    const provider = new firebase.auth.GoogleAuthProvider();
    auth.signInWithPopup(provider);
  }

  return(
    <>
    <button onClick={signInWithGoogle}>Sign in with google</button>
    <p>Do not violate the community guidelines or you will be banned for life!</p>
    </>
  )
}

function SignOut(){
  return auth.currentUser && (
    <button onClick={() => auth.signOut()}>Sign Out</button>
  )
}


function ChatRoom(){
  const messagesRef = firestore.collection('messages');
  const query = messagesRef.orderBy('createdAt').limit(25);

  const [messages] = useCollectionData(query, {idField: 'id'});

  return (
    <>
    <div>
      {messages && messages.map(msg => <ChatMessage key={msg.id} message={msg}></ChatMessage>)}
    </div>
    </>
  )
}

function ChatMessage(props){
  const {text, uid} = props.message;

  const messageClass = uid;

  return <p>{text}</p>
}


export default App;