import { useEffect, useState } from 'react'
import { api } from '../services/api'
import SyncStatus from '../components/SyncStatus'

interface DashboardStats {
  totalEmployees: number
  totalSkills: number
  totalUsers: number
  lastSync?: {
    timestamp: string
    success: boolean
    itemsSynced: number
  }
}

export default function Dashboard() {
  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: 'Mitarbeiter',
      value: stats.totalEmployees,
      color: 'text-primary-blue',
      bgColor: 'bg-bg-accent',
    },
    {
      title: 'Skills',
      value: stats.totalSkills,
      color: 'text-success',
      bgColor: 'bg-success-bg',
    },
    {
      title: 'Benutzer',
      value: stats.totalUsers,
      color: 'text-info',
      bgColor: 'bg-info-bg',
    },
  ]

  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-3 gap-6 mb-8">
        {statsCards.map((stat, index) => (
          <div key={index} className="card">
            <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>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div className="card">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">
            Letzte Synchronisation
          </h2>
          {stats.lastSync ? (
            <div className="space-y-2">
              <p className="text-body text-secondary">
                <span className="font-medium">Zeitpunkt:</span>{' '}
                {new Date(stats.lastSync.timestamp).toLocaleString('de-DE')}
              </p>
              <p className="text-body text-secondary">
                <span className="font-medium">Status:</span>{' '}
                <span className={stats.lastSync.success ? 'text-success' : 'text-error'}>
                  {stats.lastSync.success ? 'Erfolgreich' : 'Fehlgeschlagen'}
                </span>
              </p>
              <p className="text-body text-secondary">
                <span className="font-medium">Synchronisierte Elemente:</span>{' '}
                {stats.lastSync.itemsSynced}
              </p>
            </div>
          ) : (
            <p className="text-body text-tertiary">
              Noch keine Synchronisation durchgeführt
            </p>
          )}
        </div>

        <div className="card">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">
            Systemstatus
          </h2>
          <div className="space-y-2">
            <p className="text-body text-secondary">
              <span className="font-medium">Backend:</span>{' '}
              <span className="text-success">Online</span>
            </p>
            <p className="text-body text-secondary">
              <span className="font-medium">Datenbank:</span>{' '}
              <span className="text-success">Verbunden</span>
            </p>
            <p className="text-body text-secondary">
              <span className="font-medium">Version:</span> 1.0.0
            </p>
          </div>
        </div>
      </div>

      <SyncStatus />
    </div>
  )
}
