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


const OrderPage = () => {
    const {loading, data} = useProfile();
    const [orders, setOrders] = useState([]);


    useEffect(() => {
        fetch('/api/orders').then(res => {
            res.json().then(orders => {
                setOrders(orders.reverse());
            })
        })
    }, [])


    //date&time for createdAt
    function dateTime(str){
        return str.replace('T', ' ').substring(0, 16)
    }

    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'>
            {orders?.length > 0 && orders.map((order) => (
                <div key={order._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 gap-2'>
                        <div className='text-gray-700 font-semibold'>{order.userEmail}</div>
                        <div className='mb-2'>
                            {order.paid? (
                                <Link href={'/orders/'+order._id} className='bg-gray-200 text-gray-700 p-2 text-xs font-semibold'>Receipt info</Link>
                            ): (
                                <Link href={'/orders/'+order._id} className='bg-gray-200 text-gray-700 p-2 text-xs font-semibold'>Order info</Link>
                            )
                        }
                        </div>
                        <div className='text-xs text-gray-500'>{dateTime(order.createdAt)}</div>
                    </div>
                    <div className='text-xs text-center text-white font-medium'>
                        <div className={order.paid? 'bg-green-600 p-[5px] w-[50px] rounded-[4px]' : 'bg-red-600 p-[5px] w-[120px] rounded-[4px]'}>{order.paid ? 'Paid' : 'Payment required'}</div>
                    </div>
                </div>
            ))}
        </div>
    </div>
  )
}

export default OrderPage