import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../services/api'

interface DashboardStats {
  totalEmployees: number
  totalSkills: number
  totalUsers: number
}

export default function Dashboard() {
  const navigate = useNavigate()
  const [stats, setStats] = useState<DashboardStats>({
    totalEmployees: 0,
    totalSkills: 0,
    totalUsers: 0,
  })
  const [loading, setLoading] = useState(true)

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

  const fetchStats = async () => {
    try {
      const [employeesRes, hierarchyRes, usersRes] = await Promise.all([
        // Zähle nur Mitarbeitende mit verknüpftem aktivem Benutzerkonto (wie im Frontend)
        api.get('/employees/public'),
        // Zähle nur in der Hierarchie sichtbare Skills (entspricht Skill-Verwaltung)
        api.get('/skills/hierarchy'),
        api.get('/admin/users'),
      ])

      const publicEmployees = employeesRes.data.data || []
      const users = (usersRes.data.data || [])
        .filter((u: any) => u.username !== 'admin' && u.isActive !== false)

      // Summe Skills aus Hierarchie bilden
      const hierarchy = (hierarchyRes.data.data || []) as any[]
      const totalSkills = hierarchy.reduce((sum, cat) => sum + (cat.subcategories || []).reduce((s2: number, sub: any) => s2 + ((sub.skills || []).length), 0), 0)

      setStats({
        totalEmployees: publicEmployees.length,
        totalSkills,
        totalUsers: users.length,
      })
    } catch (error) {
      console.error('Failed to fetch stats:', error)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <p className="text-tertiary">Daten werden geladen...</p>
      </div>
    )
  }

  const statsCards = [
    {
      title: 'Mitarbeitende',
      value: stats.totalEmployees,
      color: 'text-primary-blue',
      bgColor: 'bg-bg-accent',
      path: '/users'
    },
    {
      title: 'Skills',
      value: stats.totalSkills,
      color: 'text-success',
      bgColor: 'bg-success-bg',
      path: '/skills'
    }
  ]

  return (
    <div>
      <h1 className="text-title-lg font-poppins font-bold text-primary mb-8">
        Dashboard
      </h1>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        {statsCards.map((stat, index) => (
          <button
            key={index}
            type="button"
            onClick={() => navigate(stat.path)}
            className="card text-left transition hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-primary-blue"
          >
            <div className={`w-16 h-16 rounded-card ${stat.bgColor} flex items-center justify-center mb-4`}>
              <span className={`text-2xl font-bold ${stat.color}`}>
                {stat.value}
              </span>
            </div>
            <h3 className="text-body font-medium text-tertiary">
              {stat.title}
            </h3>
          </button>
        ))}
      </div>

      
    </div>
  )
}
