import { useEffect, useState } from 'react'
import { adminService, Review } from '@/services/adminService'

export function ReviewsPage() {
    const [reviews, setReviews] = useState<Review[]>([])
    const [loading, setLoading] = useState(true)
    const [page, setPage] = useState(1)
    const [total, setTotal] = useState(0)

    const pageSize = 10

    useEffect(() => {
        loadReviews()
    }, [page])

    const loadReviews = async () => {
        setLoading(true)
        try {
            const data = await adminService.listReviews(page, pageSize)
            setReviews(data.reviews || [])
            setTotal(data.total)
        } catch (err) {
            console.error('Error loading reviews:', err)
        } finally {
            setLoading(false)
        }
    }

    const formatDate = (dateStr: string) => {
        return new Date(dateStr).toLocaleDateString('pt-BR', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        })
    }

    const renderStars = (rating: number) => {
        return (
            <div className="flex text-yellow-500">
                {[...Array(5)].map((_, i) => (
                    <span key={i}>
                        {i < rating ? '★' : '☆'}
                    </span>
                ))}
            </div>
        )
    }

    const totalPages = Math.ceil(total / pageSize)

    return (
        <div>
            <div className="mb-6 flex items-center justify-between">
                <h1 className="text-2xl font-bold text-gray-900">Avaliações</h1>
            </div>

            {/* Table */}
            <div className="overflow-hidden rounded-lg bg-white shadow">
                <table className="min-w-full divide-y divide-gray-200">
                    <thead className="text-white" style={{ backgroundColor: '#0F4C81' }}>
                        <tr>
                            <th className="px-4 py-3 text-left text-sm font-medium">Data</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Pedido</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Nota</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Comentário</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Comprador ID</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                        {loading ? (
                            <tr>
                                <td colSpan={5} className="py-8 text-center text-gray-500">
                                    Carregando...
                                </td>
                            </tr>
                        ) : reviews.length === 0 ? (
                            <tr>
                                <td colSpan={5} className="py-8 text-center text-gray-500">
                                    Nenhuma avaliação encontrada
                                </td>
                            </tr>
                        ) : (
                            reviews.map((review) => (
                                <tr key={review.id} className="hover:bg-gray-50">
                                    <td className="px-4 py-3 text-sm text-gray-600">
                                        {formatDate(review.created_at)}
                                    </td>
                                    <td className="px-4 py-3 text-sm font-mono text-gray-600">
                                        {review.order_id.substring(0, 8)}...
                                    </td>
                                    <td className="px-4 py-3">
                                        {renderStars(review.rating)}
                                    </td>
                                    <td className="px-4 py-3 text-sm text-gray-900">
                                        {review.comment}
                                    </td>
                                    <td className="px-4 py-3 text-xs font-mono text-gray-500">
                                        {review.buyer_id.substring(0, 8)}...
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
                <div className="mt-4 flex items-center justify-between">
                    <p className="text-sm text-gray-600">
                        Mostrando {(page - 1) * pageSize + 1} a {Math.min(page * pageSize, total)} de {total}
                    </p>
                    <div className="flex gap-2">
                        <button
                            onClick={() => setPage(page - 1)}
                            disabled={page === 1}
                            className="rounded border px-3 py-1 text-sm disabled:opacity-50"
                        >
                            Anterior
                        </button>
                        <button
                            onClick={() => setPage(page + 1)}
                            disabled={page >= totalPages}
                            className="rounded border px-3 py-1 text-sm disabled:opacity-50"
                        >
                            Próxima
                        </button>
                    </div>
                </div>
            )}
        </div>
    )
}
