"use client"
import React, { useEffect, useState } from 'react'
import UserTab from '../../components/layout/UserTab'
import useProfile from '../../components/UseProfile'
import { LiaEditSolid } from "react-icons/lia";
import Link from 'next/link';

const Userspage = () => {
    const {data, loading} = useProfile();
    const [users, setUsers] = useState([]);


    useEffect(() => {
        fetch('/api/users').then(response => {
            response.json().then(users => {
                setUsers(users)
            })
        })
    }, [])


    if(loading){
        return <p className='flex justify-center items-center'>Loading...</p>
    }
    if(!data.admin){
        return <p className='flex justify-center items-center'>Please login as an admin</p>
    }


  return (
    <div className='px-5 mb-10'>
        <UserTab isAdmin={true}/>
        <div className='max-w-md mx-auto mt-10'>
            {users?.length > 0 && users.map(user => (
                <div key={user._id} className='border p-2 my-2 w-full rounded-md outline-none border-[#DCA0AE] flex items-center justify-between'>
                    <div className='flex flex-col'>
                        <div className='text-gray-700 font-semibold'>
                            {!!user.name && (
                                <span>{user.name}</span>
                            )}
                            {!user.name && (
                                <span className='italic'>No username</span>
                            )}
                        </div>
                        <span className='text-gray-500 text-sm'>{user.email}</span>
                    </div>
                    <div>
                        <Link href={'/users/'+user._id}><LiaEditSolid className='text-green-600 text-xl'/></Link>
                    </div>
                </div>
            ))}
        </div>
    </div>
  )
}

export default Userspage