import { useEffect, useState } from 'react'
import { useAuth } from '@/context/AuthContext'
import { Shell } from '@/layouts/Shell'
import { apiClient } from '@/services/apiClient'
import { formatCents } from '@/utils/format'
import { FaChartLine, FaBoxOpen, FaReceipt, FaArrowsRotate } from 'react-icons/fa6'

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 { user } = useAuth()
    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)

    const kpiCards = data ? [
        {
            label: 'Total de Vendas',
            value: formatCurrency(data.total_sales_cents),
            icon: <FaChartLine size={28} color="black" />,
        },
        {
            label: 'Pedidos',
            value: String(data.orders_count),
            icon: <FaBoxOpen size={28} color="black" />,
        },
        {
            label: 'Ticket Médio',
            value: data.orders_count > 0
                ? formatCurrency(data.total_sales_cents / data.orders_count)
                : 'R$ 0,00',
            icon: <FaReceipt size={28} color="black" />,
        },
    ] : []

    return (
        <Shell>
            <div className="space-y-6">
                {/* Page header */}
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900">Dashboard do Vendedor</h1>
                        <p className="text-sm text-gray-500 mt-0.5">
                            Olá, {user?.name} · métricas e indicadores de performance
                        </p>
                    </div>
                    <button
                        onClick={loadDashboard}
                        className="flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold text-white hover:opacity-90 transition"
                        style={{ backgroundColor: '#0F4C81' }}
                    >
                        <FaArrowsRotate size={14} />
                        Atualizar
                    </button>
                </div>

                {/* Loading */}
                {loading && (
                    <div className="flex justify-center py-10">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2" style={{ borderColor: '#0F4C81' }}></div>
                    </div>
                )}

                {/* Error */}
                {error && (
                    <div className="rounded-lg bg-red-50 border border-red-200 p-4 text-red-700 text-sm">{error}</div>
                )}

                {data && (
                    <>
                        {/* KPI Cards */}
                        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                            {kpiCards.map((card) => (
                                <div key={card.label} className="rounded-xl bg-white p-6 shadow flex items-center gap-4">
                                    <div className="flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl bg-gray-100">
                                        {card.icon}
                                    </div>
                                    <div>
                                        <p className="text-sm text-gray-500">{card.label}</p>
                                        <p className="text-2xl font-bold text-gray-900 mt-0.5">{card.value}</p>
                                    </div>
                                </div>
                            ))}
                        </div>

                        {/* Bottom cards */}
                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            {/* Top Products */}
                            <div className="rounded-xl 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-400 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 text-xs font-bold text-white"
                                                        style={{ backgroundColor: '#0F4C81' }}
                                                    >
                                                        {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-gray-800">
                                                    {formatCurrency(product.revenue_cents)}
                                                </span>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>

                            {/* Low Stock Alerts */}
                            <div className="rounded-xl bg-white p-6 shadow-sm">
                                <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                                    <span className="text-amber-500">⚠</span>
                                    Alertas de Estoque Baixo
                                </h2>
                                {data.low_stock_alerts.length === 0 ? (
                                    <p className="text-green-600 text-sm flex items-center gap-1">
                                        <span>✓</span> 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-lg bg-red-50 px-4 py-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>
    )
}
