import { useEffect, useState } from 'react'
import { useParams, Link } from 'react-router-dom'
import { Shell } from '@/layouts/Shell'
import { apiClient } from '@/services/apiClient'
import { formatCents } from '@/utils/format'

interface OrderItem {
    id: string
    product_id: string
    quantity: number
    unit_cents: number
    batch: string
    expires_at: string
}

interface ShippingAddress {
    recipient_name: string
    street: string
    number: string
    complement?: string
    district: string
    city: string
    state: string
    zip_code: string
}

interface Order {
    id: string
    buyer_id: string
    seller_id: string
    status: string
    total_cents: number
    payment_method: string
    items: OrderItem[]
    shipping: ShippingAddress
    created_at: string
    updated_at: string
}

const statusSteps = [
    { status: 'Pendente', icon: '⏳', label: 'Pedido Criado' },
    { status: 'Pago', icon: '💳', label: 'Pagamento Confirmado' },
    { status: 'Faturado', icon: '📄', label: 'Nota Fiscal Emitida' },
    { status: 'Enviado', icon: '🚚', label: 'Pedido Enviado' },
    { status: 'Entregue', icon: '✅', label: 'Pedido Entregue' }
]

export function OrderDetailsPage() {
    const { id } = useParams<{ id: string }>()
    const [order, setOrder] = useState<Order | null>(null)
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)

    useEffect(() => {
        if (id) {
            loadOrder(id)
        }
    }, [id])

    const loadOrder = async (orderId: string) => {
        try {
            setLoading(true)
            const data = await apiClient.get<Order>(`/v1/orders/${orderId}`)
            setOrder(data)
        } catch (err) {
            console.error('Erro ao carregar pedido:', err)
            setError('Pedido não encontrado')
        } finally {
            setLoading(false)
        }
    }

    const currentStepIndex = statusSteps.findIndex(s => s.status === order?.status)

    return (
        <Shell>
            <div className="max-w-3xl mx-auto p-6">
                <Link to="/orders" className="text-blue-600 hover:underline text-sm mb-4 inline-block">
                    ← Voltar para Pedidos
                </Link>

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

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

                {order && (
                    <div className="space-y-6">
                        {/* Header */}
                        <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-200">
                            <div className="flex items-center justify-between mb-4">
                                <div>
                                    <h1 className="text-xl font-bold text-gray-900">Pedido #{order.id.slice(0, 8)}</h1>
                                    <p className="text-sm text-gray-500">
                                        Criado em {new Date(order.created_at).toLocaleString('pt-BR')}
                                    </p>
                                </div>
                                <span className={`px-3 py-1 rounded-full text-sm font-medium ${order.status === 'Entregue' ? 'bg-green-100 text-green-800' :
                                        order.status === 'Cancelado' ? 'bg-red-100 text-red-800' :
                                            'bg-blue-100 text-blue-800'
                                    }`}>
                                    {order.status}
                                </span>
                            </div>
                        </div>

                        {/* Timeline */}
                        <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-200">
                            <h2 className="text-lg font-semibold mb-6">📍 Acompanhamento</h2>
                            <div className="relative">
                                <div className="absolute left-4 top-0 bottom-0 w-0.5 bg-gray-200"></div>
                                <div className="space-y-6">
                                    {statusSteps.map((step, index) => {
                                        const isCompleted = index <= currentStepIndex
                                        const isCurrent = index === currentStepIndex
                                        return (
                                            <div key={step.status} className="relative pl-10">
                                                <div className={`absolute left-0 w-8 h-8 rounded-full flex items-center justify-center text-lg ${isCompleted ? 'bg-green-500 text-white' : 'bg-gray-200 text-gray-500'
                                                    } ${isCurrent ? 'ring-4 ring-green-200' : ''}`}>
                                                    {step.icon}
                                                </div>
                                                <div>
                                                    <p className={`font-medium ${isCompleted ? 'text-gray-900' : 'text-gray-400'}`}>
                                                        {step.label}
                                                    </p>
                                                    {isCurrent && (
                                                        <p className="text-xs text-green-600">Status atual</p>
                                                    )}
                                                </div>
                                            </div>
                                        )
                                    })}
                                </div>
                            </div>
                        </div>

                        {/* Items */}
                        <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-200">
                            <h2 className="text-lg font-semibold mb-4">📦 Itens do Pedido</h2>
                            <div className="space-y-3">
                                {order.items.map((item) => (
                                    <div key={item.id} className="flex items-center justify-between py-2 border-b border-gray-100 last:border-0">
                                        <div>
                                            <p className="font-medium">Produto #{item.product_id.slice(0, 8)}</p>
                                            <p className="text-sm text-gray-500">Lote: {item.batch} • Qtd: {item.quantity}</p>
                                        </div>
                                        <p className="font-semibold text-gray-900">{formatCents(item.unit_cents * item.quantity)}</p>
                                    </div>
                                ))}
                            </div>
                            <div className="mt-4 pt-4 border-t border-gray-200 flex justify-between">
                                <span className="font-semibold text-gray-900">Total</span>
                                <span className="text-xl font-bold text-green-600">{formatCents(order.total_cents)}</span>
                            </div>
                        </div>

                        {/* Shipping */}
                        {order.shipping && order.shipping.street && (
                            <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-200">
                                <h2 className="text-lg font-semibold mb-4">🏠 Endereço de Entrega</h2>
                                <div className="text-gray-700">
                                    <p className="font-medium">{order.shipping.recipient_name}</p>
                                    <p>{order.shipping.street}, {order.shipping.number} {order.shipping.complement && `- ${order.shipping.complement}`}</p>
                                    <p>{order.shipping.district}</p>
                                    <p>{order.shipping.city} - {order.shipping.state}</p>
                                    <p className="text-sm text-gray-500">CEP: {order.shipping.zip_code}</p>
                                </div>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </Shell>
    )
}
