import { useEffect, useState } from 'react'
import { Shell } from '../layouts/Shell'
import { apiClient } from '../services/apiClient'

interface Order {
    id: string
    buyer_id: string
    seller_id: string
    status: string
    total_cents: number
    created_at: string
}

const statusColors: Record<string, string> = {
    Pendente: 'bg-yellow-100 text-yellow-800',
    Pago: 'bg-blue-100 text-blue-800',
    Faturado: 'bg-purple-100 text-purple-800',
    Entregue: 'bg-green-100 text-green-800'
}

export function OrdersPage() {
    const [orders, setOrders] = useState<Order[]>([])
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)

    useEffect(() => {
        loadOrders()
    }, [])

    const loadOrders = async () => {
        try {
            setLoading(true)
            const response = await apiClient.get('/v1/orders')
            setOrders(response.data || [])
            setError(null)
        } catch (err) {
            setError('Erro ao carregar pedidos')
            console.error(err)
        } finally {
            setLoading(false)
        }
    }

    const updateStatus = async (orderId: string, newStatus: string) => {
        try {
            await apiClient.post(`/v1/orders/${orderId}/status`, { status: newStatus })
            await loadOrders()
        } catch (err) {
            console.error('Erro ao atualizar status:', err)
        }
    }

    const formatCurrency = (cents: number) => `R$ ${(cents / 100).toFixed(2)}`

    return (
        <Shell>
            <div className="space-y-4">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-xl font-semibold text-medicalBlue">Pedidos</h1>
                        <p className="text-sm text-gray-600">Gerenciamento de pedidos e status</p>
                    </div>
                    <button
                        onClick={loadOrders}
                        className="rounded bg-medicalBlue px-4 py-2 text-sm font-semibold text-white hover:opacity-90"
                    >
                        Atualizar
                    </button>
                </div>

                {loading && (
                    <div className="flex justify-center py-8">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-medicalBlue"></div>
                    </div>
                )}

                {error && (
                    <div className="rounded bg-red-100 p-4 text-red-700">{error}</div>
                )}

                {!loading && orders.length === 0 && (
                    <div className="rounded bg-gray-100 p-8 text-center text-gray-600">
                        Nenhum pedido encontrado
                    </div>
                )}

                <div className="space-y-3">
                    {orders.map((order) => (
                        <div key={order.id} className="rounded-lg bg-white p-4 shadow-sm">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="font-semibold text-gray-800">Pedido #{order.id.slice(0, 8)}</p>
                                    <p className="text-sm text-gray-500">
                                        {new Date(order.created_at).toLocaleDateString('pt-BR')}
                                    </p>
                                </div>
                                <div className="text-right">
                                    <p className="text-lg font-bold text-medicalBlue">
                                        {formatCurrency(order.total_cents)}
                                    </p>
                                    <span className={`inline-block rounded px-2 py-1 text-xs font-semibold ${statusColors[order.status] || 'bg-gray-100'}`}>
                                        {order.status}
                                    </span>
                                </div>
                            </div>
                            <div className="mt-3 flex gap-2">
                                {order.status === 'Pendente' && (
                                    <button
                                        onClick={() => updateStatus(order.id, 'Pago')}
                                        className="rounded bg-blue-500 px-3 py-1 text-xs text-white"
                                    >
                                        Marcar como Pago
                                    </button>
                                )}
                                {order.status === 'Pago' && (
                                    <button
                                        onClick={() => updateStatus(order.id, 'Faturado')}
                                        className="rounded bg-purple-500 px-3 py-1 text-xs text-white"
                                    >
                                        Faturar
                                    </button>
                                )}
                                {order.status === 'Faturado' && (
                                    <button
                                        onClick={() => updateStatus(order.id, 'Entregue')}
                                        className="rounded bg-green-500 px-3 py-1 text-xs text-white"
                                    >
                                        Marcar Entregue
                                    </button>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </Shell>
    )
}
