import { useEffect, useState } from 'react'
import type { Employee } from '@skillmate/shared'
import { SearchIcon } from '../components/icons'
import EmployeeCard from '../components/EmployeeCard'
import { useNavigate } from 'react-router-dom'
import { employeeApi } from '../services/api'
// Import the skill hierarchy - we'll load it dynamically in useEffect

type SkillWithStats = {
  id: string
  name: string
  category: string
  subcategory: string
  userCount: number
  levelDistribution: {
    beginner: number
    intermediate: number
    expert: number
  }
}

export default function SkillSearch() {
  const navigate = useNavigate()
  const [selectedCategories, setSelectedCategories] = useState<Set<string>>(new Set())
  const [selectedSkills, setSelectedSkills] = useState<Set<string>>(new Set())
  const [freeSearchTerm, setFreeSearchTerm] = useState('')
  const [filteredEmployees, setFilteredEmployees] = useState<Employee[]>([])
  const [allEmployees, setAllEmployees] = useState<Employee[]>([])
  const [loading, setLoading] = useState(false)
  const [hierarchy, setHierarchy] = useState<{ id: string; name: string; subcategories: { id: string; name: string; skills: { id: string; name: string }[] }[] }[]>([])
  const [allSkillsWithStats, setAllSkillsWithStats] = useState<SkillWithStats[]>([])
  const [searchSuggestions, setSearchSuggestions] = useState<string[]>([])

  useEffect(() => {
    const load = async () => {
      try {
        // Try to load static skill hierarchy
        let SKILL_HIERARCHY: any[] = []
        try {
          const skillModule = await import('../../../shared/skills.js')
          SKILL_HIERARCHY = skillModule.SKILL_HIERARCHY || []
        } catch {
          console.log('Could not load static skill hierarchy')
        }
        
        // Load hierarchy from API
        const res = await fetch(((import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api') + '/skills/hierarchy', {
          headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        })
        const data = await res.json()
        if (data?.success) {
          // Use API data if available, otherwise fallback to static hierarchy
          const apiHierarchy = data.data || []
          const combinedHierarchy = apiHierarchy.length > 0 ? apiHierarchy : SKILL_HIERARCHY
          setHierarchy(combinedHierarchy)
          
          // Calculate skill stats from employees
          const empRes = await employeeApi.getAll()
          setAllEmployees(empRes) // Store all employees for filtering
          const skillStats: Record<string, SkillWithStats> = {}
          
          // Process hierarchy to get all skills - use combined hierarchy
          const hierarchyData = combinedHierarchy
          hierarchyData.forEach((cat: any) => {
            cat.subcategories?.forEach((sub: any) => {
              sub.skills?.forEach((skill: any) => {
                skillStats[skill.id] = {
                  id: skill.id,
                  name: skill.name,
                  category: cat.id,  // Use category ID to match selectedCategories
                  subcategory: sub.name,
                  userCount: 0,
                  levelDistribution: { beginner: 0, intermediate: 0, expert: 0 }
                }
              })
            })
          })
          
          // Count employees and levels
          empRes.forEach((emp: any) => {
            emp.skills?.forEach((skill: any) => {
              if (skillStats[skill.id]) {
                skillStats[skill.id].userCount++
                const level = parseInt(skill.level) || 0
                if (level >= 1 && level <= 3) {
                  skillStats[skill.id].levelDistribution.beginner++
                } else if (level >= 4 && level <= 6) {
                  skillStats[skill.id].levelDistribution.intermediate++
                } else if (level >= 7 && level <= 10) {
                  skillStats[skill.id].levelDistribution.expert++
                }
              }
            })
          })
          
          setAllSkillsWithStats(Object.values(skillStats))
        }
      } catch (e) { /* ignore */ }
    }
    load()
  }, [])

  // Live search suggestions
  useEffect(() => {
    if (freeSearchTerm.length > 1) {
      const suggestions: string[] = []
      
      // Search in skills
      allSkillsWithStats.forEach(skill => {
        if (skill.name.toLowerCase().includes(freeSearchTerm.toLowerCase())) {
          suggestions.push(skill.name)
        }
      })
      
      // Search in categories
      hierarchy.forEach(cat => {
        if (cat.name.toLowerCase().includes(freeSearchTerm.toLowerCase())) {
          suggestions.push(cat.name)
        }
        cat.subcategories?.forEach(sub => {
          if (sub.name.toLowerCase().includes(freeSearchTerm.toLowerCase())) {
            suggestions.push(sub.name)
          }
        })
      })
      
      setSearchSuggestions(suggestions.slice(0, 5))
    } else {
      setSearchSuggestions([])
    }
  }, [freeSearchTerm, allSkillsWithStats, hierarchy])

  const toggleCategory = (categoryId: string) => {
    const newSelection = new Set(selectedCategories)
    if (newSelection.has(categoryId)) {
      newSelection.delete(categoryId)
      if (newSelection.size === 0) {
        setSelectedSkills(new Set())
        setFilteredEmployees([])
      }
    } else {
      newSelection.add(categoryId)
    }
    setSelectedCategories(newSelection)
  }

  // Toggle skill selection and filter employees
  const handleSkillClick = (skillId: string) => {
    const newSelection = new Set(selectedSkills)
    
    if (newSelection.has(skillId)) {
      newSelection.delete(skillId)
    } else {
      newSelection.add(skillId)
    }
    
    setSelectedSkills(newSelection)
    
    // Filter employees who have ANY of the selected skills
    if (newSelection.size === 0) {
      setFilteredEmployees([])
    } else {
      const filtered = allEmployees.filter(employee => 
        Array.from(newSelection).some(selectedId => 
          employee.skills?.some((skill: any) => skill.id === selectedId)
        )
      ).map(emp => {
        // Find highest skill level among selected skills
        const selectedSkillLevels = Array.from(newSelection)
          .map(selectedId => emp.skills?.find((s: any) => s.id === selectedId)?.level || 0)
          .map(level => parseInt(level) || 0)
        const maxLevel = Math.max(...selectedSkillLevels, 0)
        
        return {
          ...emp,
          selectedSkillLevel: maxLevel,
          matchedSkillsCount: selectedSkillLevels.filter(l => l > 0).length
        }
      }).sort((a: any, b: any) => {
        // Sort by number of matched skills, then by highest level
        if (a.matchedSkillsCount !== b.matchedSkillsCount) {
          return b.matchedSkillsCount - a.matchedSkillsCount
        }
        return b.selectedSkillLevel - a.selectedSkillLevel
      })
      
      setFilteredEmployees(filtered)
    }
  }

  // Live search as user types
  useEffect(() => {
    if (freeSearchTerm.length > 2) {
      const searchLower = freeSearchTerm.toLowerCase()
      const results = allEmployees.filter(employee => {
        // Search in name, department, position
        if (`${employee.firstName} ${employee.lastName}`.toLowerCase().includes(searchLower) ||
            employee.department?.toLowerCase().includes(searchLower) ||
            employee.position?.toLowerCase().includes(searchLower)) {
          return true
        }
        
        // Search in skills
        if (employee.skills?.some((skill: any) => skill.name?.toLowerCase().includes(searchLower))) {
          return true
        }
        
        // Search in specializations
        if (employee.specializations?.some((spec: any) => spec?.toLowerCase().includes(searchLower))) {
          return true
        }
        
        return false
      })
      setFilteredEmployees(results)
    } else if (freeSearchTerm.length === 0 && selectedSkills.size > 0) {
      // If search is cleared, reapply skill filters
      const filtered = allEmployees.filter(employee => 
        Array.from(selectedSkills).some(selectedId => 
          employee.skills?.some((skill: any) => skill.id === selectedId)
        )
      )
      setFilteredEmployees(filtered)
    }
  }, [freeSearchTerm, allEmployees])

  const handleReset = () => {
    setSelectedCategories(new Set())
    setSelectedSkills(new Set())
    setFreeSearchTerm('')
    setFilteredEmployees([])
    setSearchSuggestions([])
  }

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

  const getCategoryConfig = (categoryName: string) => {
    const key = categoryName.toLowerCase().replace(/[^a-z]/g, '')
    return categoryConfig[key] || { icon: '📁', color: 'bg-gray-100 text-gray-800 border-gray-300' }
  }

  const getFilteredSkills = () => {
    if (selectedCategories.size === 0) return []
    return allSkillsWithStats.filter(skill => 
      selectedCategories.has(skill.category)
    ).sort((a, b) => b.userCount - a.userCount)
  }

  const getSkillNameById = (skillId: string) => {
    for (const cat of hierarchy) {
      for (const sub of cat.subcategories || []) {
        const found = (sub.skills || []).find(s => s.id === skillId)
        if (found) return found.name
      }
    }
    return skillId
  }

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

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <div className="lg:col-span-1">
          <div className="card">
            <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">
              Filter
            </h2>

            <div className="space-y-4">
              {/* Freie Suche mit Live-Vorschlägen */}
              <div>
                <label className="block text-body font-medium text-secondary mb-2">
                  Intelligente Suche
                </label>
                <div className="relative">
                  <input
                    type="text"
                    value={freeSearchTerm}
                    onChange={(e) => setFreeSearchTerm(e.target.value)}
                    placeholder="Name, Skill, Abteilung..."
                    className="input-field w-full pl-10"
                    autoComplete="off"
                  />
                  <SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-placeholder" />
                  
                  {/* Live-Vorschläge */}
                  {searchSuggestions.length > 0 && (
                    <div className="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-border-default rounded-lg shadow-lg">
                      {searchSuggestions.map((suggestion, index) => (
                        <button
                          key={index}
                          onClick={() => {
                            setFreeSearchTerm(suggestion)
                            setSearchSuggestions([])
                          }}
                          className="w-full text-left px-4 py-2 hover:bg-bg-accent text-secondary hover:text-primary transition-colors"
                        >
                          {suggestion}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              {/* Kategorie Filter-Bubbles */}
              <div>
                <label className="block text-body font-medium text-secondary mb-2">
                  Kategorien (Mehrfachauswahl)
                </label>
                <div className="flex flex-wrap gap-2">
                  {hierarchy.map((category) => {
                    const config = getCategoryConfig(category.name)
                    const isSelected = selectedCategories.has(category.id)  // Use ID for checking
                    return (
                      <button
                        key={category.id}
                        onClick={() => toggleCategory(category.id)}  // Pass ID instead of name
                        className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all flex items-center gap-1 border-2 ${
                          isSelected 
                            ? config.color + ' shadow-md scale-105'
                            : 'bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600'
                        }`}
                      >
                        <span>{config.icon}</span>
                        <span>{category.name}</span>
                        {isSelected && <span className="ml-1">✓</span>}
                      </button>
                    )
                  })}
                </div>
              </div>

              {/* Remove old skill grid from here - will be in middle column */}
              {false && (
                <div>
                  <label className="block text-body font-medium text-secondary mb-2">
                    Verfügbare Skills ({getFilteredSkills().length})
                  </label>
                  <div className="border border-border-default rounded-card p-3 max-h-96 overflow-y-auto">
                    <div className="grid grid-cols-1 gap-2">
                      {getFilteredSkills().map((skill) => {
                        const isSelected = selectedSkills.includes(skill.id)
                        const dist = skill.levelDistribution
                        return (
                          <button
                            key={skill.id}
                            onClick={() => handleSkillToggle(skill.id)}
                            className={`p-3 rounded-lg border-2 transition-all text-left ${
                              isSelected 
                                ? 'bg-blue-50 border-blue-400 dark:bg-blue-900/20 dark:border-blue-500'
                                : 'bg-white border-gray-200 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700'
                            }`}
                          >
                            <div className="flex items-start justify-between mb-2">
                              <div>
                                <span className="font-medium text-primary">{skill.name}</span>
                                <span className="ml-2 text-xs text-tertiary">({skill.subcategory})</span>
                              </div>
                              {isSelected && <span className="text-blue-600 text-lg">✓</span>}
                            </div>
                            
                            {/* Level-Verteilung mit geometrischen Formen */}
                            <div className="flex items-center gap-3">
                              <div className="flex gap-2">
                                {dist.beginner > 0 && (
                                  <div className="relative w-6 h-6 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-6 h-6 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-6 h-6" 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" style={{ fontSize: '10px' }}>{dist.expert}</span>
                                  </div>
                                )}
                              </div>
                              <span className="text-xs text-tertiary ml-auto">
                                {skill.userCount} Mitarbeitende
                              </span>
                            </div>
                          </button>
                        )
                      })}
                    </div>
                  </div>
                </div>
              )}

              <button
                onClick={handleReset}
                className="w-full btn-secondary"
              >
                Filter zurücksetzen
              </button>
            </div>
          </div>

          {selectedSkills.size > 0 && (
            <div className="card mt-6">
              <h3 className="text-body font-poppins font-semibold text-primary mb-3">
                Ausgewählte Skills ({selectedSkills.size})
              </h3>
              <div className="space-y-2">
                {Array.from(selectedSkills).map(skillId => (
                  <div key={skillId} className="flex items-center justify-between">
                    <span className="badge badge-info text-xs">
                      {getSkillNameById(skillId)}
                    </span>
                    <button
                      onClick={() => handleSkillClick(skillId)}
                      className="text-xs text-error hover:text-red-700"
                    >
                      ×
                    </button>
                  </div>
                ))}
              </div>
              <button
                onClick={() => {
                  setSelectedSkills(new Set())
                  setFilteredEmployees([])
                }}
                className="w-full mt-3 text-xs btn-secondary"
              >
                Alle abwählen
              </button>
            </div>
          )}
        </div>

        {/* Middle column - Skills */}
        <div className="lg:col-span-2">
          <div className="card">
            <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">
              Verfügbare Skills
              {selectedCategories.size > 0 && (
                <span className="ml-2 text-body font-normal text-tertiary">
                  ({getFilteredSkills().length} Skills)
                </span>
              )}
            </h2>

            {selectedCategories.size === 0 ? (
              <div className="text-center py-12">
                <p className="text-tertiary">
                  Wählen Sie eine Kategorie aus
                </p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[600px] overflow-y-auto">
                {getFilteredSkills().map((skill) => {
                  const isSelected = selectedSkills.has(skill.id)
                  const dist = skill.levelDistribution
                  return (
                    <button
                      key={skill.id}
                      onClick={() => handleSkillClick(skill.id)}
                      className={`p-3 rounded-lg border-2 transition-all text-left ${
                        isSelected 
                          ? 'bg-blue-50 border-blue-400 shadow-md dark:bg-blue-900/20 dark:border-blue-500'
                          : 'bg-white border-gray-200 hover:bg-gray-50 hover:border-gray-300 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700'
                      }`}
                    >
                      <div className="flex items-start justify-between mb-2">
                        <div>
                          <span className="font-medium text-primary">{skill.name}</span>
                          {isSelected && <span className="ml-2 text-blue-600">✓</span>}
                        </div>
                      </div>
                      
                      {/* Level-Verteilung mit geometrischen Formen */}
                      <div className="flex items-center gap-3">
                        <div className="flex gap-2">
                          {dist.beginner > 0 && (
                            <div className="relative w-6 h-6 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-6 h-6 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-6 h-6" 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" style={{ fontSize: '10px' }}>{dist.expert}</span>
                            </div>
                          )}
                        </div>
                        <span className="text-xs text-tertiary ml-auto">
                          {skill.userCount} total
                        </span>
                      </div>
                    </button>
                  )
                })}
              </div>
            )}
          </div>
        </div>

        {/* Right column - Employees */}
        <div className="lg:col-span-1">
          <div className="card">
            <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">
              Mitarbeitende
              {filteredEmployees.length > 0 && (
                <span className="ml-2 text-body font-normal text-tertiary">
                  ({filteredEmployees.length})
                </span>
              )}
            </h2>

            {selectedSkills.size === 0 && freeSearchTerm.length === 0 ? (
              <div className="text-center py-8">
                <p className="text-tertiary text-sm">
                  Wählen Sie einen Skill aus
                </p>
              </div>
            ) : filteredEmployees.length === 0 ? (
              <div className="text-center py-8">
                <p className="text-tertiary text-sm">
                  Keine Mitarbeitenden gefunden
                </p>
              </div>
            ) : (
              <div className="space-y-2 max-h-[600px] overflow-y-auto">
                {filteredEmployees.map((employee: any) => {
                  const skillLevel = parseInt(employee.selectedSkillLevel) || 0
                  return (
                    <button
                      key={employee.id}
                      onClick={() => navigate(`/employees/${employee.id}`)}
                      className="w-full p-3 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors text-left"
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="font-medium text-primary">
                            {employee.firstName} {employee.lastName}
                          </div>
                          <div className="text-xs text-tertiary">
                            {employee.position}
                            {employee.officialTitle ? ` • ${employee.officialTitle}` : ''}
                          </div>
                        </div>
                        {selectedSkills.size > 0 && (
                          <div className="flex items-center gap-1">
                            {skillLevel >= 7 ? (
                              <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" title={`Experte (Level ${skillLevel})`}>
                                <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>
                            ) : skillLevel >= 4 ? (
                              <div className="w-5 h-5 bg-green-500 flex items-center justify-center" title={`Fortgeschritten (Level ${skillLevel})`}>
                              </div>
                            ) : skillLevel >= 1 ? (
                              <div className="w-5 h-5 bg-red-500 rounded-full flex items-center justify-center" title={`Anfänger (Level ${skillLevel})`}>
                              </div>
                            ) : null}
                          </div>
                        )}
                      </div>
                    </button>
                  )
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
