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

interface SellerDashboardData {
    seller_id: string
    total_sales_cents: number
    orders_count: number
    top_products: Array<{
        product_id: string
        name: string
        total_quantity: number
        revenue_cents: number
    }>
    low_stock_alerts: Array<{
        id: string
        name: string
        stock: number
    }>
}

export function SellerDashboardPage() {
    const [data, setData] = useState<SellerDashboardData | null>(null)
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)

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

    const loadDashboard = async () => {
        try {
            setLoading(true)
            const payload = await apiClient.get<SellerDashboardData>('/v1/dashboard/seller') ?? {}
            setData({
                seller_id: payload.seller_id ?? '',
                total_sales_cents: payload.total_sales_cents ?? 0,
                orders_count: payload.orders_count ?? 0,
                top_products: Array.isArray(payload.top_products) ? payload.top_products : [],
                low_stock_alerts: Array.isArray(payload.low_stock_alerts) ? payload.low_stock_alerts : []
            })
            setError(null)
        } catch (err) {
            setError('Erro ao carregar dashboard')
            console.error(err)
        } finally {
            setLoading(false)
        }
    }

    const formatCurrency = (cents: number | undefined | null) => formatCents(cents)

    return (
        <Shell>
            <div className="space-y-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-xl font-semibold text-medicalBlue">Dashboard do Vendedor</h1>
                        <p className="text-sm text-gray-600">Métricas e indicadores de performance</p>
                    </div>
                    <div className="flex gap-3">
                        <Link
                            to="/search"
                            className="rounded bg-green-600 px-4 py-2 text-sm font-semibold text-white hover:bg-green-700"
                        >
                            🛒 Comprar Medicamentos
                        </Link>
                        <button
                            onClick={loadDashboard}
                            className="rounded bg-medicalBlue px-4 py-2 text-sm font-semibold text-white"
                        >
                            Atualizar
                        </button>
                    </div>
                </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>
                )}

                {data && (
                    <>
                        {/* KPI Cards */}
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div className="rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 p-6 text-white">
                                <p className="text-sm opacity-80">Total de Vendas</p>
                                <p className="text-3xl font-bold">{formatCurrency(data.total_sales_cents)}</p>
                            </div>
                            <div className="rounded-lg bg-gradient-to-br from-green-500 to-green-600 p-6 text-white">
                                <p className="text-sm opacity-80">Pedidos</p>
                                <p className="text-3xl font-bold">{data.orders_count}</p>
                            </div>
                            <div className="rounded-lg bg-gradient-to-br from-purple-500 to-purple-600 p-6 text-white">
                                <p className="text-sm opacity-80">Ticket Médio</p>
                                <p className="text-3xl font-bold">
                                    {data.orders_count > 0
                                        ? formatCurrency(data.total_sales_cents / data.orders_count)
                                        : 'R$ 0,00'}
                                </p>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            {/* Top Products */}
                            <div className="rounded-lg bg-white p-6 shadow-sm">
                                <h2 className="text-lg font-semibold text-gray-800 mb-4">Top Produtos</h2>
                                {data.top_products.length === 0 ? (
                                    <p className="text-gray-500 text-sm">Nenhum produto vendido ainda</p>
                                ) : (
                                    <div className="space-y-3">
                                        {data.top_products.map((product, idx) => (
                                            <div key={product.product_id} className="flex items-center justify-between">
                                                <div className="flex items-center gap-3">
                                                    <span className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-100 text-sm font-semibold">
                                                        {idx + 1}
                                                    </span>
                                                    <div>
                                                        <p className="font-medium text-gray-800">{product.name}</p>
                                                        <p className="text-xs text-gray-500">{product.total_quantity} unidades</p>
                                                    </div>
                                                </div>
                                                <span className="font-semibold text-medicalBlue">
                                                    {formatCurrency(product.revenue_cents)}
                                                </span>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>

                            {/* Low Stock Alerts */}
                            <div className="rounded-lg bg-white p-6 shadow-sm">
                                <h2 className="text-lg font-semibold text-gray-800 mb-4">
                                    ⚠️ Alertas de Estoque Baixo
                                </h2>
                                {data.low_stock_alerts.length === 0 ? (
                                    <p className="text-green-600 text-sm">✓ Todos os produtos com estoque adequado</p>
                                ) : (
                                    <div className="space-y-3">
                                        {data.low_stock_alerts.map((product) => (
                                            <div
                                                key={product.id}
                                                className="flex items-center justify-between rounded bg-red-50 p-3"
                                            >
                                                <span className="font-medium text-gray-800">{product.name}</span>
                                                <span className="rounded bg-red-100 px-2 py-1 text-xs font-semibold text-red-800">
                                                    {product.stock} restantes
                                                </span>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>
                        </div>
                    </>
                )}
            </div>
        </Shell>
    )
}
