import { useEffect, useState } from 'react'
import { adminService, Shipment } from '../../services/adminService'

export function LogisticsPage() {
    const [shipments, setShipments] = useState<Shipment[]>([])
    const [loading, setLoading] = useState(true)
    const [page, setPage] = useState(1)
    const [total, setTotal] = useState(0)

    const pageSize = 10

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

    const loadShipments = async () => {
        setLoading(true)
        try {
            const data = await adminService.listShipments(page, pageSize)
            setShipments(data.shipments || [])
            setTotal(data.total)
        } catch (err) {
            console.error('Error loading shipments:', 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 getStatusBadge = (status: string) => {
        const colors: Record<string, string> = {
            'Enviado': 'bg-blue-100 text-blue-800',
            'Entregue': 'bg-green-100 text-green-800',
            'Pendente': 'bg-yellow-100 text-yellow-800',
        }
        return (
            <span className={`rounded-full px-2 py-1 text-xs font-medium ${colors[status] || 'bg-gray-100 text-gray-800'}`}>
                {status}
            </span>
        )
    }

    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">Logística de Envios</h1>
            </div>

            {/* Table */}
            <div className="overflow-hidden rounded-lg bg-white shadow">
                <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-blue-900 text-white">
                        <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">Transportadora</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Rastreio</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">External</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Status</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Pedido ID</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                        {loading ? (
                            <tr>
                                <td colSpan={6} className="py-8 text-center text-gray-500">
                                    Carregando...
                                </td>
                            </tr>
                        ) : shipments.length === 0 ? (
                            <tr>
                                <td colSpan={6} className="py-8 text-center text-gray-500">
                                    Nenhum envio encontrado
                                </td>
                            </tr>
                        ) : (
                            shipments.map((shipment) => (
                                <tr key={shipment.id} className="hover:bg-gray-50">
                                    <td className="px-4 py-3 text-sm text-gray-600">
                                        {formatDate(shipment.created_at)}
                                    </td>
                                    <td className="px-4 py-3 text-sm font-medium text-gray-900">
                                        {shipment.carrier}
                                    </td>
                                    <td className="px-4 py-3 text-sm font-mono text-blue-600">
                                        {shipment.tracking_code}
                                    </td>
                                    <td className="px-4 py-3 text-sm text-gray-500">
                                        {shipment.external_tracking || '-'}
                                    </td>
                                    <td className="px-4 py-3">
                                        {getStatusBadge(shipment.status)}
                                    </td>
                                    <td className="px-4 py-3 text-xs font-mono text-gray-500">
                                        {shipment.order_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>
    )
}
