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

interface DashboardStats {
    totalUsers: number
    totalCompanies: number
    totalProducts: number
    totalOrders: number
}

export function DashboardHome() {
    const [stats, setStats] = useState<DashboardStats>({
        totalUsers: 0,
        totalCompanies: 0,
        totalProducts: 0,
        totalOrders: 0
    })
    const [loading, setLoading] = useState(true)

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

    const extractCount = (payload: unknown): number => {
        if (Array.isArray(payload)) {
            return payload.length
        }

        if (payload && typeof payload === 'object') {
            const record = payload as Record<string, unknown>

            if (typeof record.total === 'number') {
                return record.total
            }

            const possibleCollections = [
                record.items,
                record.users,
                record.companies,
                record.products,
                record.orders
            ]

            for (const collection of possibleCollections) {
                if (Array.isArray(collection)) {
                    return collection.length
                }
            }
        }

        return 0
    }

    const loadStats = async () => {
        setLoading(true)
        try {
            // Load counts from each endpoint
            const [users, companies, products, orders] = await Promise.all([
                apiClient.get('/v1/users?page=1&page_size=1').catch(() => ({ total: 0 })),
                apiClient.get('/v1/companies').catch(() => ([])),
                apiClient.get('/v1/products').catch(() => ([])),
                apiClient.get('/v1/orders').catch(() => ([]))
            ])

            setStats({
                totalUsers: extractCount(users),
                totalCompanies: extractCount(companies),
                totalProducts: extractCount(products),
                totalOrders: extractCount(orders)
            })
        } catch (err) {
            console.error('Error loading stats:', err)
        } finally {
            setLoading(false)
        }
    }

    const cards = [
        { title: 'Usuários', value: stats.totalUsers, icon: '👥', color: 'from-blue-500 to-blue-600' },
        { title: 'Empresas', value: stats.totalCompanies, icon: '🏢', color: 'from-purple-500 to-purple-600' },
        { title: 'Produtos', value: stats.totalProducts, icon: '💊', color: 'from-green-500 to-green-600' },
        { title: 'Pedidos', value: stats.totalOrders, icon: '📦', color: 'from-orange-500 to-orange-600' }
    ]

    return (
        <div>
            <h1 className="mb-6 text-2xl font-bold text-gray-900">Painel Administrativo</h1>

            {/* Stats Cards */}
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
                {cards.map((card) => (
                    <div
                        key={card.title}
                        className={`rounded-xl bg-gradient-to-br ${card.color} p-6 text-white shadow-lg`}
                    >
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-white/80">{card.title}</p>
                                <p className="mt-1 text-3xl font-bold">
                                    {loading ? '...' : card.value.toLocaleString('pt-BR')}
                                </p>
                            </div>
                            <span className="text-4xl opacity-80">{card.icon}</span>
                        </div>
                    </div>
                ))}
            </div>

            {/* Quick Actions */}
            <div className="mt-8">
                <h2 className="mb-4 text-lg font-semibold text-gray-800">Ações Rápidas</h2>
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                    <a href="/dashboard/users" className="rounded-lg bg-white p-4 shadow hover:shadow-md transition-shadow">
                        <h3 className="font-medium text-gray-900">Gerenciar Usuários</h3>
                        <p className="mt-1 text-sm text-gray-500">Criar, editar e remover usuários</p>
                    </a>
                    <a href="/dashboard/companies" className="rounded-lg bg-white p-4 shadow hover:shadow-md transition-shadow">
                        <h3 className="font-medium text-gray-900">Gerenciar Empresas</h3>
                        <p className="mt-1 text-sm text-gray-500">Verificar e administrar farmácias</p>
                    </a>
                    <a href="/dashboard/products" className="rounded-lg bg-white p-4 shadow hover:shadow-md transition-shadow">
                        <h3 className="font-medium text-gray-900">Gerenciar Produtos</h3>
                        <p className="mt-1 text-sm text-gray-500">Catálogo de medicamentos</p>
                    </a>
                    <a href="/dashboard/orders" className="rounded-lg bg-white p-4 shadow hover:shadow-md transition-shadow">
                        <h3 className="font-medium text-gray-900">Gerenciar Pedidos</h3>
                        <p className="mt-1 text-sm text-gray-500">Acompanhar e atualizar status</p>
                    </a>
                </div>
            </div>
        </div>
    )
}
