"use client"

import { useEffect,useState } from "react"
import { collection,getDocs,updateDoc,doc } from "firebase/firestore"
import { db } from "@/lib/firebase"

export default function UsersPage(){

const [users,setUsers] = useState<any[]>([])

useEffect(()=>{

const loadUsers = async()=>{

const snap = await getDocs(collection(db,"users"))

const data:any[] = []

snap.forEach((d)=>{
data.push({
id:d.id,
...d.data()
})
})

setUsers(data)

}

loadUsers()

},[])

const toggleActive = async(user:any)=>{

await updateDoc(doc(db,"users",user.id),{
isActive:!user.isActive
})

setUsers(users.map(u=>{
if(u.id===user.id){
return {...u,isActive:!u.isActive}
}
return u
}))

}

return(

<div className="p-10">

<h1 className="text-3xl font-bold mb-8">
Restaurants
</h1>

<table className="w-full border">

<thead>

<tr className="bg-gray-100">
<th className="p-3">Restaurant</th>
<th>Email</th>
<th>Phone</th>
<th>Status</th>
<th>Action</th>
</tr>

</thead>

<tbody>

{users.map(user=>(

<tr key={user.id} className="border-t">

<td className="p-3">{user.restaurant}</td>
<td>{user.email}</td>
<td>{user.phone}</td>

<td>
{user.isActive ? "Active" : "Disabled"}
</td>

<td>

<button
onClick={()=>toggleActive(user)}
className="bg-black text-white px-4 py-2 rounded"
>

{user.isActive ? "Deactivate" : "Activate"}

</button>

</td>

</tr>

))}

</tbody>

</table>

</div>

)

}