import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { api } from '../services/api'

type Skill = {
  id: string
  name: string
  category?: string
  description?: string | null
  userCount?: number
  tags?: string[]
  levelDistribution?: {
    beginner: number
    intermediate: number
    expert: number
  }
  typeKey?: string
  typeName?: string
  typeIcon?: string
}

type Category = {
  id: string
  name: string
  icon?: string
  color?: string
  skillCount?: number
}

type SkillType = {
  key: string
  id: string
  name: string
  categoryId: string
  categoryName: string
  icon: string
  color: string
}

type ViewMode = 'grid' | 'category'

export default function SkillManagement() {
  const [skills, setSkills] = useState<Skill[]>([])
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [viewMode, setViewMode] = useState<ViewMode>('grid')
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategories, setSelectedCategories] = useState<Set<string>>(new Set())
  const [selectedSkills, setSelectedSkills] = useState<Set<string>>(new Set())
  const [sortBy, setSortBy] = useState<'name' | 'users' | 'category'>('name')
  const [employeeCounts, setEmployeeCounts] = useState<Record<string, number>>({})
  const [levelDistributions, setLevelDistributions] = useState<Record<string, { beginner: number, intermediate: number, expert: number }>>({})
  const [skillTypes, setSkillTypes] = useState<SkillType[]>([])
  const [selectedTypes, setSelectedTypes] = useState<Set<string>>(new Set())
  const [expandedTypes, setExpandedTypes] = useState<Set<string>>(new Set())
  const sectionRefs = useRef<Record<string, HTMLDivElement | null>>({})
  const lastExpansionRef = useRef<{ key: string; prevTop: number | null } | null>(null)
  
  // Modal states
  const [showSkillModal, setShowSkillModal] = useState(false)
  const [editingSkill, setEditingSkill] = useState<Skill | null>(null)
  const [showImportModal, setShowImportModal] = useState(false)
  
  // Form states for skill modal
  const [skillForm, setSkillForm] = useState({
    name: '',
    description: '',
    category: '',
    typeKey: '',
    tags: [] as string[]
  })

  // Category icon and color mapping
  const categoryConfig: Record<string, { icon: string, color: string }> = {
    'communication': { icon: '💬', color: 'bg-green-100 text-green-800' },
    'technical': { icon: '💻', color: 'bg-blue-100 text-blue-800' },
    'operational': { icon: '🎯', color: 'bg-orange-100 text-orange-800' },
    'analytical': { icon: '📊', color: 'bg-purple-100 text-purple-800' },
    'certifications': { icon: '📜', color: 'bg-yellow-100 text-yellow-800' },
  }

  const typeIconFallback = '📁'

  const typeIconMap: Record<string, string> = {
    languages: '🌐',
    interpersonal: '🤝',
    presentation: '🗣️',
    moderation: '🎙️',
    negotiation: '⚖️',
    security: '🛡️',
  }

  // Predefined tags
  const availableTags = [
    'Programmierung', 'Datenanalyse', 'Forensik', 'Machine Learning',
    'Ermittlung', 'Kommunikation', 'Führung', 'Sicherheit',
    'Waffen', 'Fahrzeuge', 'Medizin', 'Recht'
  ]

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

  useEffect(() => {
    if (!editingSkill && !skillForm.category && categories.length > 0) {
      setSkillForm(prev => ({ ...prev, category: categories[0].id }))
    }
  }, [categories, editingSkill, skillForm.category])

  async function loadData() {
    // First fetch employee counts, then skills with those counts
    const { counts, distributions } = await fetchEmployeeCountsAndDistributions()
    await fetchSkills(counts, distributions)
  }

  async function fetchSkills(counts?: Record<string, number>, distributions?: Record<string, { beginner: number, intermediate: number, expert: number }>) {
    try {
      setLoading(true)
      const res = await api.get('/skills/hierarchy')
      const hierarchy = res.data.data || []
      
      // Use passed data or state
      const skillCounts = counts || employeeCounts
      const skillDistributions = distributions || levelDistributions
      
      // Extract categories and flatten skills
      const extractedCategories: Category[] = []
      const flatSkills: Skill[] = []
      const seenCategories = new Set<string>()
      const collectedTypes: SkillType[] = []
      const seenTypeKeys = new Set<string>()
      
      hierarchy.forEach((cat: any) => {
        // Add category if not seen
        if (!seenCategories.has(cat.id)) {
          seenCategories.add(cat.id)
          const config = categoryConfig[cat.id] || { icon: '📁', color: 'bg-gray-100 text-gray-800' }
          extractedCategories.push({
            id: cat.id,
            name: cat.name,
            icon: config.icon,
            color: config.color,
            skillCount: 0
          })
        }
        
        const catName = cat.name

        cat.subcategories?.forEach((sub: any) => {
          const typeKey = `${cat.id}.${sub.id}`
          if (!seenTypeKeys.has(typeKey)) {
            seenTypeKeys.add(typeKey)
            const typeIcon = typeIconMap[sub.id] || typeIconFallback
            const typeColor = categoryConfig[cat.id]?.color || 'bg-gray-100 text-gray-800'
            collectedTypes.push({
              key: typeKey,
              id: sub.id,
              name: sub.name,
              categoryId: cat.id,
              categoryName: catName,
              icon: typeIcon,
              color: typeColor
            })
          }

          sub.skills?.forEach((skill: any) => {
            flatSkills.push({
              ...skill,
              category: cat.id,
              typeKey,
              typeName: sub.name,
              typeIcon: typeIconMap[sub.id] || typeIconFallback,
              tags: [cat.name, sub.name],
              userCount: skillCounts[skill.id] || 0,
              levelDistribution: skillDistributions[skill.id] || { beginner: 0, intermediate: 0, expert: 0 }
            })
          })
        })
      })
      
      // Update skill counts for categories
      extractedCategories.forEach(cat => {
        cat.skillCount = flatSkills.filter(s => s.category === cat.id).length
      })
      
      setCategories(extractedCategories)
      setSkills(flatSkills)
      setSkillTypes(collectedTypes.sort((a, b) => a.name.localeCompare(b.name)))
    } catch (e) {
      setError('Skills konnten nicht geladen werden')
    } finally {
      setLoading(false)
    }
  }

  async function fetchEmployeeCountsAndDistributions() {
    try {
      // Fetch employees and count skills with level distribution
      const res = await api.get('/employees')
      const employees = res.data.data || []
      const counts: Record<string, number> = {}
      const distributions: Record<string, { beginner: number, intermediate: number, expert: number }> = {}
      
      employees.forEach((emp: any) => {
        emp.skills?.forEach((skill: any) => {
          counts[skill.id] = (counts[skill.id] || 0) + 1
          
          // Initialize distribution if not exists
          if (!distributions[skill.id]) {
            distributions[skill.id] = { beginner: 0, intermediate: 0, expert: 0 }
          }
          
          // Parse level and categorize
          const level = parseInt(skill.level) || 0
          if (level >= 1 && level <= 3) {
            distributions[skill.id].beginner++
          } else if (level >= 4 && level <= 6) {
            distributions[skill.id].intermediate++
          } else if (level >= 7 && level <= 10) {
            distributions[skill.id].expert++
          }
        })
      })
      
      setEmployeeCounts(counts)
      setLevelDistributions(distributions)
      return { counts, distributions }
    } catch (e) {
      console.error('Could not fetch employee counts')
      return { counts: {}, distributions: {} }
    }
  }

  const filteredAndSortedSkills = skills
    .filter(skill => {
      const matchesSearch = skill.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                            skill.description?.toLowerCase().includes(searchQuery.toLowerCase())
      const matchesCategory = selectedCategories.size === 0 || selectedCategories.has(skill.category || '')
      const matchesType = selectedTypes.size === 0 || (skill.typeKey && selectedTypes.has(skill.typeKey))
      return matchesSearch && matchesCategory && matchesType
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name)
        case 'users':
          return (employeeCounts[b.id] || 0) - (employeeCounts[a.id] || 0)
        case 'category':
          const catA = categories.find(c => c.id === a.category)?.name || ''
          const catB = categories.find(c => c.id === b.category)?.name || ''
          return catA.localeCompare(catB)
        default:
          return 0
      }
    })

  const quickStats = {
    total: skills.length,
    categories: categories.length,
    newThisWeek: Math.floor(skills.length * 0.15)
  }

  const typeMetaMap = new Map(skillTypes.map(type => [type.key, type]))
  const fallbackTypeMeta: SkillType = {
    key: '__other',
    id: 'other',
    name: 'Weitere Skills',
    categoryId: 'other',
    categoryName: 'Weitere',
    icon: typeIconFallback,
    color: 'bg-gray-100 text-gray-800'
  }

  const groupedSkills = filteredAndSortedSkills.reduce<Map<string, Skill[]>>((acc, skill) => {
    const key = skill.typeKey && typeMetaMap.has(skill.typeKey) ? skill.typeKey : '__other'
    if (!acc.has(key)) {
      acc.set(key, [])
    }
    acc.get(key)!.push(skill)
    return acc
  }, new Map())

  const typeKeysInResults = new Set(groupedSkills.keys())

  const filteredSkillTypes = skillTypes.filter(type => {
    const categoryMatch = selectedCategories.size === 0 || selectedCategories.has(type.categoryId)
    return categoryMatch && typeKeysInResults.has(type.key)
  })

  const displayedTypeChips = filteredSkillTypes.length > 0 ? filteredSkillTypes : skillTypes.filter(type => typeKeysInResults.has(type.key))

  const toggleTypeFilter = (key: string) => {
    const updated = new Set(selectedTypes)
    if (updated.has(key)) {
      updated.delete(key)
    } else {
      updated.add(key)
    }
    setSelectedTypes(updated)
  }

  const toggleTypeExpansion = (key: string) => {
    const section = sectionRefs.current[key]
    const prevTop = section ? section.getBoundingClientRect().top : null
    lastExpansionRef.current = { key, prevTop }
    setExpandedTypes(prev => {
      const updated = new Set(prev)
      if (updated.has(key)) {
        updated.delete(key)
      } else {
        updated.add(key)
      }
      return updated
    })
  }

  useLayoutEffect(() => {
    if (!lastExpansionRef.current) return
    const { key, prevTop } = lastExpansionRef.current
    lastExpansionRef.current = null
    if (prevTop === null) return
    const section = sectionRefs.current[key]
    if (!section) return
    const newTop = section.getBoundingClientRect().top
    const delta = newTop - prevTop
    if (delta > 1) {
      window.scrollBy({ top: delta, behavior: 'auto' })
    }
  }, [expandedTypes])

  const getTypeMeta = (key: string): SkillType => {
    if (key === '__other') return fallbackTypeMeta
    return typeMetaMap.get(key) || fallbackTypeMeta
  }

  const sortedTypeKeys = Array.from(groupedSkills.keys()).sort((a, b) => {
    const metaA = getTypeMeta(a)
    const metaB = getTypeMeta(b)
    if (metaA.categoryName !== metaB.categoryName) {
      return metaA.categoryName.localeCompare(metaB.categoryName)
    }
    return metaA.name.localeCompare(metaB.name)
  })

  function TypeSection({ typeKey }: { typeKey: string }) {
    const skillsForType = groupedSkills.get(typeKey) || []
    if (skillsForType.length === 0) return null
    const typeMeta = getTypeMeta(typeKey)
    const isExpanded = expandedTypes.has(typeKey)
    const visibleSkills = isExpanded ? skillsForType : skillsForType.slice(0, 3)
    const hiddenCount = skillsForType.length - visibleSkills.length

    return (
      <div
        key={typeKey}
        ref={el => {
          if (el) {
            sectionRefs.current[typeKey] = el
          } else {
            delete sectionRefs.current[typeKey]
          }
        }}
        className="mb-8"
      >
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <span className="text-xl" aria-hidden>{typeMeta.icon}</span>
            <div>
              <h3 className="text-lg font-semibold text-primary">{typeMeta.name}</h3>
              <p className="text-xs text-secondary">{typeMeta.categoryName}</p>
            </div>
          </div>
          <span className="text-sm text-tertiary">{skillsForType.length} Skills</span>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {visibleSkills.map(skill => (
            <SkillCard key={skill.id} skill={skill} />
          ))}
        </div>

        {hiddenCount > 0 && (
          <div className="mt-3">
            <button
              type="button"
              onClick={() => toggleTypeExpansion(typeKey)}
              className="text-sm text-blue-600 hover:text-blue-800"
            >
              {isExpanded ? 'Weniger anzeigen' : `Mehr anzeigen (+${hiddenCount})`}
            </button>
          </div>
        )}
      </div>
    )
  }

  function openSkillModal(skill?: Skill) {
    if (skill) {
      setEditingSkill(skill)
      const categoryId = skill.category || ''
      const typeKey = skill.typeKey || ''
      setSkillForm({
        name: skill.name,
        description: skill.description || '',
        category: categoryId,
        typeKey,
        tags: skill.tags || []
      })
    } else {
      setEditingSkill(null)
      setSkillForm({
        name: '',
        description: '',
        category: '',
        typeKey: '',
        tags: []
      })
    }
    setShowSkillModal(true)
  }

  async function saveSkill() {
    try {
      const payload = {
        name: skillForm.name,
        description: skillForm.description,
        category: skillForm.typeKey || skillForm.category
      }

      if (!payload.category || payload.category.indexOf('.') === -1) {
        setError('Bitte einen Skill-Typ auswählen')
        return
      }

      if (editingSkill) {
        await api.put(`/skills/${editingSkill.id}`, payload)
      } else {
        await api.post('/skills', payload)
      }
      setShowSkillModal(false)
      loadData()
    } catch (e) {
      setError('Skill konnte nicht gespeichert werden')
    }
  }

  async function deleteSkill(id: string) {
    if (!confirm('Skill wirklich löschen?')) return
    try {
      await api.delete(`/skills/${id}`)
      loadData()
    } catch (e) {
      setError('Skill konnte nicht gelöscht werden')
    }
  }

  function toggleSkillSelection(skillId: string) {
    const newSelection = new Set(selectedSkills)
    if (newSelection.has(skillId)) {
      newSelection.delete(skillId)
    } else {
      newSelection.add(skillId)
    }
    setSelectedSkills(newSelection)
  }

  async function bulkDelete() {
    if (!confirm(`${selectedSkills.size} Skills wirklich löschen?`)) return
    try {
      for (const skillId of selectedSkills) {
        await api.delete(`/skills/${skillId}`)
      }
      setSelectedSkills(new Set())
      loadData()
    } catch (e) {
      setError('Skills konnten nicht gelöscht werden')
    }
  }

  function exportSkills() {
    const data = filteredAndSortedSkills.map(s => ({
      Name: s.name,
      Beschreibung: s.description,
      Kategorie: categories.find(c => c.id === s.category)?.name || s.category,
      Typ: s.typeName,
      Tags: s.tags?.join(', ')
    }))
    const csv = [
      Object.keys(data[0]).join(','),
      ...data.map(row => Object.values(row).map(v => `"${v || ''}"`).join(','))
    ].join('\n')
    
    const blob = new Blob([csv], { type: 'text/csv' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'skills-export.csv'
    a.click()
  }

  function SkillCard({ skill }: { skill: Skill }) {
    const category = categories.find(c => c.id === skill.category)
    const dist = skill.levelDistribution || { beginner: 0, intermediate: 0, expert: 0 }

    return (
      <div className="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow border border-border-default">
        <div className="flex items-start justify-between mb-3">
          <h3 className="font-semibold text-primary">{skill.name}</h3>
          <input
            type="checkbox"
            checked={selectedSkills.has(skill.id)}
            onChange={() => toggleSkillSelection(skill.id)}
            className="w-5 h-5 rounded border-gray-300"
          />
        </div>
        
        <div className="flex gap-2 mb-3">
          {dist.beginner > 0 && (
            <div className="relative w-8 h-8 bg-red-500 rounded-full flex items-center justify-center" title={`${dist.beginner} Anfänger`}>
              <span className="text-white text-xs font-bold">{dist.beginner}</span>
            </div>
          )}
          {dist.intermediate > 0 && (
            <div className="relative w-8 h-8 bg-green-500 flex items-center justify-center" title={`${dist.intermediate} Fortgeschrittene`}>
              <span className="text-white text-xs font-bold">{dist.intermediate}</span>
            </div>
          )}
          {dist.expert > 0 && (
            <div className="relative flex items-center justify-center" title={`${dist.expert} Experten`}>
              <svg className="w-8 h-8" viewBox="0 0 24 24" fill="none">
                <path 
                  d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22 7 14.14 2 9.27l6.91-1.01L12 2z" 
                  fill="rgb(147 51 234)" 
                />
              </svg>
              <span className="absolute text-white text-xs font-bold">{dist.expert}</span>
            </div>
          )}
          {(dist.beginner + dist.intermediate + dist.expert) === 0 && (
            <span className="text-gray-400 text-sm">Keine Zuordnungen</span>
          )}
        </div>
        
        {skill.description && (
          <p className="text-sm text-secondary mb-3 line-clamp-2">{skill.description}</p>
        )}
        
        <div className="flex items-start justify-between gap-2 text-sm">
          <div className="space-y-1">
            <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${category?.color || 'bg-gray-100'}`}>
              <span className="flex-shrink-0">{category?.icon}</span>
              <span className="ml-1">{category?.name}</span>
            </span>
            {skill.typeName && (
              <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-200">
                <span className="mr-1">{skill.typeIcon || typeIconFallback}</span>
                {skill.typeName}
              </span>
            )}
          </div>
          <span className="text-tertiary flex-shrink-0">👥 {employeeCounts[skill.id] || skill.userCount || 0}</span>
        </div>
        
        <div className="flex gap-2 mt-3">
          <button
            onClick={() => openSkillModal(skill)}
            className="text-xs text-blue-600 hover:text-blue-800"
          >
            Bearbeiten
          </button>
          <button
            onClick={() => deleteSkill(skill.id)}
            className="text-xs text-red-600 hover:text-red-800"
          >
            Löschen
          </button>
        </div>
      </div>
    )
  }

  const categorySkillsMap = categories.reduce<Map<string, Skill[]>>((acc, category) => {
    const skillsForCategory = filteredAndSortedSkills.filter(skill => skill.category === category.id)
    if (skillsForCategory.length > 0) {
      acc.set(category.id, skillsForCategory)
    }
    return acc
  }, new Map())

  const visibleCategories = categories.filter(category => categorySkillsMap.has(category.id))

  function CategoryView() {
    if (visibleCategories.length === 0) {
      return (
        <div className="bg-white dark:bg-gray-800 rounded-lg border border-dashed border-gray-300 dark:border-gray-600 p-8 text-center text-secondary">
          Keine Kategorien mit passenden Skills gefunden. Filter zurücksetzen?
        </div>
      )
    }

    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {visibleCategories.map(category => {
          const categorySkills = categorySkillsMap.get(category.id) || []
          return (
            <div key={category.id} className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold flex items-center gap-2">
                  <span className="text-2xl">{category.icon}</span>
                  {category.name}
                </h3>
                <span className="text-sm text-gray-500">{categorySkills.length} Skills</span>
              </div>

              <div className="space-y-2 max-h-64 overflow-y-auto">
                {categorySkills.slice(0, 10).map(skill => (
                  <div
                    key={skill.id}
                    className="flex items-center justify-between p-2 hover:bg-gray-50 dark:hover:bg-gray-700 rounded cursor-pointer"
                    onClick={() => openSkillModal(skill)}
                  >
                    <span className="text-sm">{skill.name}</span>
                    <span className="text-xs text-gray-400">👥 {employeeCounts[skill.id] || skill.userCount || 0}</span>
                  </div>
                ))}
                {categorySkills.length > 10 && (
                  <div className="text-sm text-center text-gray-500 pt-2">
                    +{categorySkills.length - 10} weitere
                  </div>
                )}
              </div>

              <button
                onClick={() => {
                  setSkillForm(prev => ({ ...prev, category: category.id, typeKey: '' }))
                  openSkillModal()
                }}
                className="w-full mt-4 text-sm text-blue-600 hover:text-blue-800"
              >
                + Skill hinzufügen
              </button>
            </div>
          )
        })}
      </div>
    )
  }

  return (
    <div>
      {/* Header */}
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-primary mb-2">Skills Management</h1>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => setShowImportModal(true)}
            className="px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            Import
          </button>
          <button
            onClick={exportSkills}
            className="px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            Export
          </button>
        </div>
      </div>

      {/* Search and Stats */}
      <div className="mb-6">
        <div className="flex gap-4 items-center mb-4">
          <div className="flex-1">
            <input
              type="text"
              placeholder="🔍 Skills suchen..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-800"
            />
          </div>
          <button
            onClick={() => openSkillModal()}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            + Neuer Skill
          </button>
        </div>

        {/* Quick Stats */}
        <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
          <div className="text-sm text-gray-600 dark:text-gray-400">
            <span className="font-semibold text-gray-900 dark:text-gray-100">{quickStats.total}</span> Skills • 
            <span className="font-semibold text-gray-900 dark:text-gray-100 ml-2">{quickStats.categories}</span> Kategorien • 
            <span className="font-semibold text-gray-900 dark:text-gray-100 ml-2">{quickStats.newThisWeek}</span> neue diese Woche
          </div>
        </div>
      </div>

      {/* Filters and View Toggle */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as 'name' | 'users' | 'category')}
              className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-800"
            >
              <option value="name">Nach Name</option>
              <option value="users">Nach Nutzerzahl</option>
              <option value="category">Nach Kategorie</option>
            </select>
            
            {selectedSkills.size > 0 && (
              <button
                onClick={bulkDelete}
                className="px-3 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
              >
                {selectedSkills.size} ausgewählte löschen
              </button>
            )}
          </div>

          <div className="flex bg-gray-200 dark:bg-gray-700 rounded-lg p-1">
            <button
              onClick={() => setViewMode('grid')}
              className={`px-3 py-1 rounded ${viewMode === 'grid' ? 'bg-white dark:bg-gray-600 shadow' : ''}`}
            >
              Grid View
            </button>
            <button
              onClick={() => setViewMode('category')}
              className={`px-3 py-1 rounded ${viewMode === 'category' ? 'bg-white dark:bg-gray-600 shadow' : ''}`}
            >
              Category View
            </button>
          </div>
        </div>
        
        <div className="flex flex-wrap gap-2">
          {categories.map(cat => (
            <button
              key={cat.id}
              onClick={() => {
                const newSelection = new Set(selectedCategories)
                if (newSelection.has(cat.id)) {
                  newSelection.delete(cat.id)
                } else {
                  newSelection.add(cat.id)
                }
                setSelectedCategories(newSelection)
              }}
              className={`px-3 py-1.5 rounded-full text-sm font-medium transition-colors flex items-center gap-1 ${
                selectedCategories.has(cat.id)
                  ? cat.color
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'
              }`}
            >
              <span>{cat.icon}</span>
              <span>{cat.name}</span>
              {selectedCategories.has(cat.id) && <span className="ml-1">✓</span>}
            </button>
          ))}
          
          {selectedCategories.size > 0 && (
            <button
              onClick={() => setSelectedCategories(new Set())}
              className="px-3 py-1.5 rounded-full text-sm font-medium bg-gray-200 text-gray-700 hover:bg-gray-300 dark:bg-gray-600 dark:text-gray-300 dark:hover:bg-gray-500"
            >
              Alle anzeigen
            </button>
          )}
        </div>

        {displayedTypeChips.length > 0 && (
          <div className="mt-4 space-y-2">
            <h3 className="text-sm font-medium text-secondary">Skill-Typen</h3>
            <div className="flex flex-wrap gap-2">
              {displayedTypeChips.map(type => {
                const isActive = selectedTypes.has(type.key)
                const count = groupedSkills.get(type.key)?.length || 0
                if (count === 0) return null
                return (
                  <button
                    key={type.key}
                    onClick={() => toggleTypeFilter(type.key)}
                    className={`px-3 py-1.5 rounded-full text-sm font-medium transition-colors flex items-center gap-1 ${
                      isActive
                        ? 'bg-blue-600 text-white shadow'
                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600'
                    }`}
                  >
                    <span>{type.icon}</span>
                    <span>{type.name}</span>
                    <span className="text-xs opacity-75">({count})</span>
                  </button>
                )
              })}

              {selectedTypes.size > 0 && (
                <button
                  onClick={() => setSelectedTypes(new Set())}
                  className="px-3 py-1.5 rounded-full text-sm font-medium bg-gray-200 text-gray-700 hover:bg-gray-300 dark:bg-gray-600 dark:text-gray-300 dark:hover:bg-gray-500"
                >
                  Alle Typen
                </button>
              )}
            </div>
          </div>
        )}

      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg mb-6">
          {error}
        </div>
      )}

      {/* Main Content */}
      {loading ? (
        <div className="text-center py-12">
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
          <p className="mt-2 text-gray-600">Lade Skills...</p>
        </div>
      ) : (
        <>
          {viewMode === 'grid' && (
            <div>
              {sortedTypeKeys.map(typeKey => (
                <TypeSection key={typeKey} typeKey={typeKey} />
              ))}
            </div>
          )}
          
          {viewMode === 'category' && <CategoryView />}
        </>
      )}

      {/* Skill Modal */}
      {showSkillModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-2xl font-bold">
                  {editingSkill ? 'Skill bearbeiten' : 'Neuer Skill'}
                </h2>
                <button
                  onClick={() => setShowSkillModal(false)}
                  className="text-gray-500 hover:text-gray-700 text-2xl"
                >
                  ×
                </button>
              </div>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium mb-2">Name *</label>
                  <input
                    type="text"
                    value={skillForm.name}
                    onChange={(e) => setSkillForm(prev => ({ ...prev, name: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
                    placeholder="z.B. Python"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2">Beschreibung</label>
                  <textarea
                    value={skillForm.description}
                    onChange={(e) => setSkillForm(prev => ({ ...prev, description: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
                    rows={3}
                    placeholder="Beschreibung des Skills..."
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2">Hauptkategorie</label>
                  <select
                    value={skillForm.category}
                    onChange={(e) => {
                      const newCategory = e.target.value
                      setSkillForm(prev => ({
                        ...prev,
                        category: newCategory,
                        typeKey: prev.typeKey.startsWith(`${newCategory}.`) ? prev.typeKey : ''
                      }))
                    }}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
                  >
                    <option value="">Kategorie wählen...</option>
                    {categories.map(cat => (
                      <option key={cat.id} value={cat.id}>{cat.name}</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2">Skill-Typ</label>
                  <select
                    value={skillForm.typeKey}
                    onChange={(e) => setSkillForm(prev => ({ ...prev, typeKey: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
                    disabled={!skillForm.category}
                  >
                    <option value="">{skillForm.category ? 'Skill-Typ wählen...' : 'Bitte zuerst eine Kategorie wählen'}</option>
                    {skillTypes
                      .filter(type => type.categoryId === skillForm.category)
                      .map(type => (
                        <option key={type.key} value={type.key}>
                          {type.name}
                        </option>
                      ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2">Tags (Mehrfachzuordnung)</label>
                  <div className="border border-gray-300 rounded-lg p-3 dark:border-gray-600">
                    <div className="flex flex-wrap gap-2">
                      {availableTags.map(tag => (
                        <button
                          key={tag}
                          onClick={() => {
                            setSkillForm(prev => ({
                              ...prev,
                              tags: prev.tags.includes(tag) 
                                ? prev.tags.filter(t => t !== tag)
                                : [...prev.tags, tag]
                            }))
                          }}
                          className={`px-3 py-1 rounded-full text-sm ${
                            skillForm.tags.includes(tag)
                              ? 'bg-blue-600 text-white'
                              : 'bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-300'
                          }`}
                        >
                          {tag} {skillForm.tags.includes(tag) && '✓'}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2">Skill-Level Definition (1-10 Skala)</label>
                  <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-3 text-sm space-y-1">
                    <div className="flex items-center gap-2">
                      <span className="text-red-600">1-3</span> Anfänger (Grundkenntnisse)
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-green-600">4-6</span> Fortgeschritten (Solide Anwendungskenntnisse)
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-purple-600">7-10</span> Experte (Führungsexperte, Spezialist)
                    </div>
                  </div>
                </div>

              </div>

              <div className="flex justify-end gap-3 mt-6">
                <button
                  onClick={() => setShowSkillModal(false)}
                  className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700"
                >
                  Abbrechen
                </button>
                <button
                  onClick={saveSkill}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  Speichern
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Import Modal */}
      {showImportModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg max-w-md w-full p-6">
            <h2 className="text-xl font-bold mb-4">Skills importieren</h2>
            <div className="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-8 text-center">
              <p className="text-gray-600 dark:text-gray-400 mb-4">
                CSV-Datei hier ablegen oder
              </p>
              <input
                type="file"
                accept=".csv"
                className="hidden"
                id="file-upload"
                onChange={(e) => {
                  // Handle file upload
                  console.log('File upload:', e.target.files?.[0])
                  setShowImportModal(false)
                }}
              />
              <label
                htmlFor="file-upload"
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer"
              >
                Datei auswählen
              </label>
            </div>
            <div className="mt-4 text-sm text-gray-600 dark:text-gray-400">
              Format: Name, Beschreibung, Kategorie, Tags (kommagetrennt)
            </div>
            <div className="flex justify-end gap-3 mt-4">
              <button
                onClick={() => setShowImportModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700"
              >
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
