import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { employeeApi } from '../services/api'
import { useAuthStore } from '../stores/authStore'

interface DashboardStats {
  totalEmployees: number
  totalSkills: number
  recentEmployees: number
  availableEmployees: number
}

export default function Dashboard() {
  const navigate = useNavigate()
  const { user } = useAuthStore()
  const [stats, setStats] = useState<DashboardStats>({
    totalEmployees: 0,
    totalSkills: 0,
    recentEmployees: 0,
    availableEmployees: 0,
  })
  const [employees, setEmployees] = useState<any[]>([])
  const [trendWindow, setTrendWindow] = useState<'today' | 7 | 30>('today')

  useEffect(() => {
    fetchStats()
  }, [])
  
  const fetchStats = async () => {
    try {
      const employees = await employeeApi.getAll()
      setEmployees(employees)
      const totalSkills = employees.reduce((sum: number, emp: any) => sum + emp.skills.length, 0)
      const availableEmployees = employees.filter((emp: any) => emp.availability === 'available').length
      
      setStats({
        totalEmployees: employees.length,
        totalSkills: totalSkills,
        recentEmployees: employees.filter((emp: any) => {
          const created = new Date(emp.createdAt)
          const weekAgo = new Date()
          weekAgo.setDate(weekAgo.getDate() - 7)
          return created > weekAgo
        }).length,
        availableEmployees: availableEmployees,
      })
    } catch (error) {
      console.error('Failed to fetch stats:', error)
      // Fallback zu Demo-Daten
      setStats({
        totalEmployees: 0,
        totalSkills: 0,
        recentEmployees: 0,
        availableEmployees: 0,
      })
      setEmployees([])
    } finally {
      // Loading complete
    }
  }

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

  // Trends: Top-Kompetenzen im Zeitraum (basierend auf aktualisierten Profilen)
  const topSkills = useMemo(() => {
    if (!employees.length) return [] as { name: string; count: number }[]
    const since = new Date()
    if (trendWindow === 'today') {
      since.setHours(0, 0, 0, 0)
    } else {
      since.setDate(since.getDate() - trendWindow)
    }
    const recent = employees.filter((e: any) => {
      const updated = new Date(e.updatedAt)
      return !isNaN(updated.getTime()) && updated > since
    })
    const counts = new Map<string, number>()
    for (const emp of recent) {
      const skills = (emp.skills || []) as { name?: string; id: string }[]
      for (const s of skills) {
        const key = (s && (s as any).name) || (s && (s as any).id) || 'Unbenannt'
        counts.set(key, (counts.get(key) || 0) + 1)
      }
    }
    const arr = Array.from(counts.entries()).map(([name, count]) => ({ name, count }))
    arr.sort((a, b) => b.count - a.count)
    return arr.slice(0, 5)
  }, [employees, trendWindow])

  // Profilqualität (mein Profil): Kontakt & Dienststelle + ob Skills vorhanden
  const me = useMemo(() => {
    if (!user?.employeeId) return null
    return employees.find(e => e.id === user.employeeId) || null
  }, [employees, user?.employeeId])

  const profileQuality = useMemo(() => {
    if (!me) return { percent: 0, missing: ['Profil wird geladen oder nicht verknüpft'] as string[], detailed: [] as { key: string; label: string; ok: boolean }[] }
    const checks: { key: string; label: string; ok: boolean }[] = [
      { key: 'firstName', label: 'Vorname', ok: !!me.firstName },
      { key: 'lastName', label: 'Nachname', ok: !!me.lastName },
      { key: 'email', label: 'E-Mail', ok: !!me.email },
      { key: 'department', label: 'Dienststelle', ok: !!me.department },
      { key: 'position', label: 'Position', ok: !!me.position },
      { key: 'phone', label: 'Telefon', ok: !!me.phone && me.phone !== 'Nicht angegeben' },
      { key: 'mobile', label: 'Mobil', ok: !!me.mobile },
      { key: 'office', label: 'Büro', ok: !!me.office },
      { key: 'employeeNumber', label: 'NW-Kennung', ok: !!me.employeeNumber },
      { key: 'skills', label: 'Mindestens eine Kompetenz erfasst', ok: Array.isArray(me.skills) && me.skills.length > 0 },
    ]
    const total = checks.length
    const done = checks.filter(c => c.ok).length
    const percent = Math.round((done / total) * 100)
    const missing = checks.filter(c => !c.ok).map(c => c.label)
    const detailed = checks
    return { percent, missing, detailed }
  }, [me])

  const qualityBarColor = (percent: number) => {
    if (percent <= 33) return 'bg-red-500 dark:bg-red-700'
    if (percent <= 66) return 'bg-green-500 dark:bg-green-700'
    return 'bg-purple-500 dark:bg-purple-700'
  }

  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 lg:grid-cols-4 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">
        {/* Trends */}
        <div className="card">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-title-card font-poppins font-semibold text-primary">Trends</h2>
            <div className="flex gap-2">
              <button
                className={`px-3 py-1 rounded-input border border-border-default text-body ${trendWindow === 'today' ? 'bg-bg-accent text-primary-blue' : 'bg-white dark:bg-dark-bg-secondary'}`}
                onClick={() => setTrendWindow('today')}
              >
                Heute
              </button>
              <button
                className={`px-3 py-1 rounded-input border border-border-default text-body ${trendWindow === 7 ? 'bg-bg-accent text-primary-blue' : 'bg-white dark:bg-dark-bg-secondary'}`}
                onClick={() => setTrendWindow(7)}
              >
                7 Tage
              </button>
              <button
                className={`px-3 py-1 rounded-input border border-border-default text-body ${trendWindow === 30 ? 'bg-bg-accent text-primary-blue' : 'bg-white dark:bg-dark-bg-secondary'}`}
                onClick={() => setTrendWindow(30)}
              >
                30 Tage
              </button>
            </div>
          </div>
          <div className="space-y-2">
            {topSkills.length === 0 ? (
              <p className="text-tertiary">Keine Daten im ausgewählten Zeitraum.</p>
            ) : (
              topSkills.map((s, idx) => (
                <div key={s.name + idx} className="flex items-center justify-between border-b border-border-default dark:border-dark-border py-2">
                  <span className="text-secondary">{s.name}</span>
                  <span className="text-tertiary">{s.count} Profile</span>
                </div>
              ))
            )}
            <p className="text-help text-tertiary mt-2">Basis: Profile mit Aktualisierung im Zeitraum.</p>
          </div>
        </div>

        {/* Profilqualität */}
        <div className="card">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">Profilqualität</h2>
          {!user?.employeeId ? (
            <p className="text-tertiary">Kein Mitarbeitendenprofil mit Ihrem Nutzer verknüpft.</p>
          ) : (
            <>
              <div className="w-full h-3 bg-bg-gray dark:bg-dark-primary rounded-input overflow-hidden">
                <div
                  className={`h-full transition-all ${qualityBarColor(profileQuality.percent)}`}
                  style={{ width: `${profileQuality.percent}%` }}
                />
              </div>
              <div className="flex items-center justify-between mt-2">
                <span className="text-secondary font-medium">{profileQuality.percent}% vollständig</span>
                <button onClick={() => navigate('/profile')} className="text-body text-primary-blue hover:underline">Mein Profil bearbeiten</button>
              </div>
              <div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2">
                {profileQuality.detailed.map((c, i) => (
                  <div key={i} className="flex items-center justify-between px-3 py-2 rounded-input border border-border-default dark:border-dark-border bg-white dark:bg-dark-bg-secondary">
                    <span className="text-body text-secondary">{c.label}</span>
                    {c.ok ? (
                      <span className="text-green-600 text-sm">✓</span>
                    ) : (
                      <span className="text-red-600 text-sm">• fehlt</span>
                    )}
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
        <div className="card">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">
            Schnellzugriff
          </h2>
          <div className="space-y-3">
            <button
              onClick={() => navigate('/employees')}
              className="w-full btn-secondary"
            >
              Mitarbeitende verwalten
            </button>
            <button
              onClick={() => navigate('/search')}
              className="w-full btn-secondary"
            >
              Nach Skills suchen
            </button>
            <button
              onClick={() => navigate('/profile')}
              className="w-full btn-secondary"
            >
              Mein Profil bearbeiten
            </button>
          </div>
        </div>

        <div className="card">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">
            Letzte Aktivitäten
          </h2>
          <div className="space-y-2">
            <p className="text-sm text-tertiary">
              Keine aktuellen Aktivitäten
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
