'use client'

import fetchData from "@/api/fetch-data"
import { toastError } from "@/services/custom-toast"
import { useLocale, useTranslations } from "next-intl"
import { useEffect, useState } from "react"
import FallbackImage from "../../shared/FallbackImage"
import Loading from "../../shared/Loading"

export default function ProductsOrders({ token }) {
    const t = useTranslations('vendor')
    const locale = useLocale()
    const [isLoading, setIsLoading] = useState(false)
    const [error, setError] = useState(null)
    const [products, setProducts] = useState([])

    async function getOrders() {
        setIsLoading(true)
        const { data, error, message } = await fetchData({
            endPoint: "/user/products/orders/600",
            token,
            locale
        })
        if (error) {
            setError(message)
        } else {
            setProducts(data?.users_product || [])
        }
        setIsLoading(false)
    }

    useEffect(() => {
        getOrders()
    }, [locale])

    if (error) {
        toastError(error)
        return null // Prevent rendering if there's an error
    }

    if (isLoading) return <Loading />

    return (
        <section>
            <h2 className="text-xl font-bold mb-4">{t('orders')}</h2>
            <ul className=" flex gap-4 flex-wrap">
                {products.map((product, index) => (
                    <li key={index} className="p-4 border h-full rounded-lg shadow-md flex-grow flex-basis-300 w-96">
                        <FallbackImage
                            src={product.userimage}
                            alt={`${product.username} ${product.userlastname}`}
                            className="w-16 h-16 rounded-full mb-2"
                        />
                        <h3 className="text-lg font-semibold">
                            {product.username} {product.userlastname}
                        </h3>
                        <p className="text-sm text-gray-700">{product.proname}</p>
                    </li>
                ))}
            </ul>
        </section>
    )
}
