import { useEffect, useState } from 'react'
import type { Employee } from '@skillmate/shared'
import { employeeApi } from '../services/api'
import { SearchIcon } from '../components/icons'

type TeamPosition = {
  id: string
  title: string
  assignedEmployeeId?: string
}

type SkillInfo = {
  id: string
  name: string
  count: number
  category: string
}

type Category = {
  id: string
  name: string
  icon?: string
}

export default function TeamZusammenstellung() {
  const [employees, setEmployees] = useState<Employee[]>([])
  const [allSkills, setAllSkills] = useState<SkillInfo[]>([])
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(true)
  
  // Team state
  const [teamName, setTeamName] = useState('Neues Team')
  const [teamPositions, setTeamPositions] = useState<TeamPosition[]>([])
  
  // Filter state
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedCategories, setSelectedCategories] = useState<Set<string>>(new Set())
  const [selectedSkills, setSelectedSkills] = useState<Set<string>>(new Set())
  const [selectedDepartment, setSelectedDepartment] = useState<string>('')
  const [selectedPosition, setSelectedPosition] = useState<string>('')
  const [onlyAvailable, setOnlyAvailable] = useState(true)
  
  // UI state
  const [assigningEmployee, setAssigningEmployee] = useState<string | null>(null)
  
  const API_BASE = (import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api'
  const PUBLIC_BASE = (import.meta as any).env?.VITE_API_PUBLIC_URL || API_BASE.replace(/\/api$/, '')
  const toPublic = (p?: string | null) => (p && p.startsWith('/uploads/')) ? `${PUBLIC_BASE}${p}` : (p || '')

  useEffect(() => {
    const load = async () => {
      setLoading(true)
      try {
        // Load static skill hierarchy if available
        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')
        }
        
        const [empList, hierRes] = await Promise.all([
          employeeApi.getAll(),
          fetch(API_BASE + '/skills/hierarchy', {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
          }).then(r => r.json())
        ])
        
        setEmployees(empList || [])
        
        // Use API data if available, otherwise fallback to static hierarchy
        const apiHierarchy = hierRes?.success ? hierRes.data : []
        const combinedHierarchy = apiHierarchy.length > 0 ? apiHierarchy : SKILL_HIERARCHY
        
        // Extract categories
        const extractedCategories: Category[] = combinedHierarchy.map((cat: any) => ({
          id: cat.id,
          name: cat.name,
          icon: getCategoryIcon(cat.id)
        }))
        setCategories(extractedCategories)
        
        // Calculate skill popularity
        const skillCounts: Record<string, SkillInfo> = {}
        
        // Initialize all skills
        combinedHierarchy.forEach((cat: any) => {
          cat.subcategories?.forEach((sub: any) => {
            sub.skills?.forEach((skill: any) => {
              skillCounts[skill.id] = {
                id: skill.id,
                name: skill.name,
                count: 0,
                category: cat.id
              }
            })
          })
        })
        
        // Count employee skills
        empList.forEach((emp: any) => {
          emp.skills?.forEach((skill: any) => {
            if (skillCounts[skill.id]) {
              skillCounts[skill.id].count++
            }
          })
        })
        
        // Sort by popularity and take top skills
        const sortedSkills = Object.values(skillCounts)
          .filter(s => s.count > 0)
          .sort((a, b) => b.count - a.count)
        
        setAllSkills(sortedSkills)
      } catch (e) {
        console.error('Error loading data:', e)
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  // Category configuration
  const getCategoryIcon = (categoryId: string) => {
    const icons: Record<string, string> = {
      'communication': '💬',
      'technical': '💻',
      'operational': '🎯',
      'analytical': '📊',
      'certifications': '📜'
    }
    return icons[categoryId] || '📁'
  }

  const getCategoryColor = (categoryId: string) => {
    const colors: Record<string, string> = {
      'communication': 'bg-blue-100 text-blue-800 border-blue-300',
      'technical': 'bg-green-100 text-green-800 border-green-300',
      'operational': 'bg-orange-100 text-orange-800 border-orange-300',
      'analytical': 'bg-purple-100 text-purple-800 border-purple-300',
      'certifications': 'bg-yellow-100 text-yellow-800 border-yellow-300'
    }
    return colors[categoryId] || 'bg-gray-100 text-gray-800 border-gray-300'
  }

  // Get unique departments and positions
  const departments = Array.from(new Set(employees.map(e => e.department).filter(Boolean)))
  const positions = Array.from(new Set(employees.map(e => e.position).filter(Boolean)))

  // Toggle category selection
  const toggleCategory = (categoryId: string) => {
    const newSelection = new Set(selectedCategories)
    if (newSelection.has(categoryId)) {
      newSelection.delete(categoryId)
    } else {
      newSelection.add(categoryId)
    }
    setSelectedCategories(newSelection)
  }

  // Get filtered skills based on selected categories
  const getFilteredSkills = () => {
    if (selectedCategories.size === 0) {
      return [] // Return empty array when no categories selected
    }
    return allSkills.filter(skill => 
      selectedCategories.has(skill.category) && skill.count > 0
    )
  }

  // Toggle skill selection
  const toggleSkill = (skillId: string) => {
    const newSelection = new Set(selectedSkills)
    if (newSelection.has(skillId)) {
      newSelection.delete(skillId)
    } else {
      newSelection.add(skillId)
    }
    setSelectedSkills(newSelection)
  }

  // Calculate match score
  const calculateMatchScore = (employee: Employee) => {
    if (selectedSkills.size === 0) return 0
    
    // Create set of employee's skills and languages
    const employeeSkillIds = new Set<string>()
    
    // Add regular skills
    employee.skills?.forEach(skill => {
      employeeSkillIds.add(skill.id)
    })
    
    // Add language skills with proper mapping
    const languageCodeMap: Record<string, string> = {
      'Deutsch': 'de', 'German': 'de',
      'Englisch': 'en', 'English': 'en',
      'Französisch': 'fr', 'French': 'fr',
      'Spanisch': 'es', 'Spanish': 'es',
      'Italienisch': 'it', 'Italian': 'it',
      'Russisch': 'ru', 'Russian': 'ru',
      'Arabisch': 'ar', 'Arabic': 'ar',
      'Türkisch': 'tr', 'Turkish': 'tr',
      'Polnisch': 'pl', 'Polish': 'pl',
      'Chinesisch': 'zh', 'Chinese': 'zh',
      'Farsi/Persisch': 'fa', 'Farsi': 'fa', 'Persian': 'fa'
    }
    
    employee.languages?.forEach((lang: any) => {
      const skillId = languageCodeMap[lang.code] || lang.code
      employeeSkillIds.add(skillId)
    })
    
    // Count matches
    const matches = Array.from(selectedSkills).filter(skillId =>
      employeeSkillIds.has(skillId)
    )
    
    return Math.round((matches.length / selectedSkills.size) * 100)
  }

  // Filter and sort employees
  const getFilteredEmployees = () => {
    // No filters active? Return empty array
    if (!searchTerm && !selectedDepartment && !selectedPosition && selectedSkills.size === 0) {
      return []
    }

    let filtered = employees

    // Search filter
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase()
      filtered = filtered.filter(emp =>
        `${emp.firstName} ${emp.lastName}`.toLowerCase().includes(searchLower) ||
        emp.skills?.some(s => s.name?.toLowerCase().includes(searchLower))
      )
    }

    // Department filter
    if (selectedDepartment) {
      filtered = filtered.filter(emp => emp.department === selectedDepartment)
    }

    // Position filter
    if (selectedPosition) {
      filtered = filtered.filter(emp => emp.position === selectedPosition)
    }

    // Availability filter
    if (onlyAvailable) {
      const assignedIds = teamPositions.map(p => p.assignedEmployeeId).filter(Boolean)
      filtered = filtered.filter(emp => !assignedIds.includes(emp.id))
    }

    // Skill filter and scoring
    if (selectedSkills.size > 0) {
      return filtered
        .map(emp => ({
          ...emp,
          matchScore: calculateMatchScore(emp)
        }))
        .filter((emp: any) => emp.matchScore > 0)
        .sort((a: any, b: any) => b.matchScore - a.matchScore)
    }

    return filtered
  }

  // Add new team position
  const addTeamPosition = () => {
    const newPosition: TeamPosition = {
      id: `pos_${Date.now()}`,
      title: `Position ${teamPositions.length + 1}`
    }
    setTeamPositions([...teamPositions, newPosition])
  }

  // Update position title
  const updatePositionTitle = (posId: string, title: string) => {
    setTeamPositions(prev => prev.map(pos =>
      pos.id === posId ? { ...pos, title } : pos
    ))
  }

  // Remove team position
  const removeTeamPosition = (posId: string) => {
    setTeamPositions(prev => prev.filter(pos => pos.id !== posId))
  }

  // Start assigning employee
  const startAssignment = (employeeId: string) => {
    if (teamPositions.length === 0) {
      addTeamPosition()
      setTimeout(() => setAssigningEmployee(employeeId), 100)
    } else {
      setAssigningEmployee(employeeId)
    }
  }

  // Assign employee to position
  const assignEmployee = (positionId: string) => {
    if (assigningEmployee) {
      setTeamPositions(prev => prev.map(pos =>
        pos.id === positionId ? { ...pos, assignedEmployeeId: assigningEmployee } : pos
      ))
      setAssigningEmployee(null)
    }
  }

  // Unassign employee from position
  const unassignEmployee = (positionId: string) => {
    setTeamPositions(prev => prev.map(pos =>
      pos.id === positionId ? { ...pos, assignedEmployeeId: undefined } : pos
    ))
  }

  // Get employee by ID
  const getEmployeeById = (employeeId: string) => {
    return employees.find(emp => emp.id === employeeId)
  }

  // Get team completeness based on skill coverage
  const getTeamCompleteness = () => {
    // If no skills selected, return 0
    if (selectedSkills.size === 0) return 0
    
    // Get all skills from assigned team members
    const teamSkills = new Set<string>()
    teamPositions.forEach(pos => {
      if (pos.assignedEmployeeId) {
        const employee = getEmployeeById(pos.assignedEmployeeId)
        
        // Add regular skills
        employee?.skills?.forEach(skill => {
          teamSkills.add(skill.id)
        })
        
        // Add language skills - map language codes to skill IDs
        employee?.languages?.forEach((lang: any) => {
          // Map common language codes to skill IDs used in SKILL_HIERARCHY
          const languageCodeMap: Record<string, string> = {
            'Deutsch': 'de',
            'Englisch': 'en',
            'Französisch': 'fr',
            'Spanisch': 'es',
            'Italienisch': 'it',
            'Russisch': 'ru',
            'Arabisch': 'ar',
            'Türkisch': 'tr',
            'Polnisch': 'pl',
            'Chinesisch': 'zh',
            'Farsi/Persisch': 'fa',
            'German': 'de',
            'English': 'en',
            'French': 'fr',
            'Spanish': 'es',
            'Italian': 'it',
            'Russian': 'ru',
            'Arabic': 'ar',
            'Turkish': 'tr',
            'Polish': 'pl',
            'Chinese': 'zh',
            'Farsi': 'fa',
            'Persian': 'fa'
          }
          
          const skillId = languageCodeMap[lang.code] || lang.code
          teamSkills.add(skillId)
        })
      }
    })
    
    // Calculate how many selected skills are covered by the team
    let coveredCount = 0
    selectedSkills.forEach(skillId => {
      if (teamSkills.has(skillId)) {
        coveredCount++
      }
    })
    
    // Return percentage of selected skills that are covered
    return Math.round((coveredCount / selectedSkills.size) * 100)
  }

  // Get assigned skills summary
  const getAssignedSkills = () => {
    const skills = new Map<string, number>()
    teamPositions.forEach(pos => {
      if (pos.assignedEmployeeId) {
        const employee = getEmployeeById(pos.assignedEmployeeId)
        employee?.skills?.forEach(skill => {
          skills.set(skill.id, (skills.get(skill.id) || 0) + 1)
        })
      }
    })
    return skills
  }

  const filteredEmployees = getFilteredEmployees()
  const assignedSkills = getAssignedSkills()

  if (loading) {
    return (
      <div className="card">
        <p className="text-tertiary">Lade Daten…</p>
      </div>
    )
  }

  return (
    <div className="h-full">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-title-lg font-poppins font-bold text-primary mb-2">
          Team-Zusammenstellung
        </h1>
        <p className="text-tertiary">
          Wählen Sie Skills oder nutzen Sie die Filter, um passende Mitarbeitende zu finden und Ihrem Team zuzuweisen.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Area - 2 columns wide on large screens */}
        <div className="lg:col-span-2">
          {/* Search and Filters */}
          <div className="card mb-6">
            <div className="space-y-4">
              {/* Search Bar */}
              <div className="relative">
                <input
                  type="text"
                  placeholder="Suche nach Name, Skill, Position..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="input-field w-full pl-10"
                />
                <SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-placeholder" />
              </div>

              {/* Quick Filters */}
              <div className="flex flex-wrap gap-2">
                <select
                  value={selectedDepartment}
                  onChange={(e) => setSelectedDepartment(e.target.value)}
                  className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm"
                >
                  <option value="">Alle Dienststellen</option>
                  {departments.map(dept => (
                    <option key={dept} value={dept}>{dept}</option>
                  ))}
                </select>

                <select
                  value={selectedPosition}
                  onChange={(e) => setSelectedPosition(e.target.value)}
                  className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm"
                >
                  <option value="">Alle Positionen</option>
                  {positions.map(pos => (
                    <option key={pos} value={pos}>{pos}</option>
                  ))}
                </select>

                <label className="flex items-center gap-2 px-3 py-1.5 border border-gray-300 rounded-lg text-sm cursor-pointer hover:bg-gray-50">
                  <input
                    type="checkbox"
                    checked={onlyAvailable}
                    onChange={(e) => setOnlyAvailable(e.target.checked)}
                    className="w-4 h-4"
                  />
                  <span>Nur verfügbare</span>
                </label>

                {(selectedDepartment || selectedPosition || searchTerm || selectedCategories.size > 0 || selectedSkills.size > 0) && (
                  <button
                    onClick={() => {
                      setSearchTerm('')
                      setSelectedDepartment('')
                      setSelectedPosition('')
                      setSelectedCategories(new Set())
                      setSelectedSkills(new Set())
                    }}
                    className="px-3 py-1.5 text-sm text-red-600 hover:text-red-800"
                  >
                    Filter zurücksetzen
                  </button>
                )}
              </div>
            </div>
          </div>

          {/* Skill Cloud */}
          <div className="card mb-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-title-card font-poppins font-semibold text-primary">
                Skills auswählen
              </h2>
              {(selectedCategories.size > 0 || selectedSkills.size > 0) && (
                <button
                  onClick={() => {
                    setSelectedCategories(new Set())
                    setSelectedSkills(new Set())
                  }}
                  className="text-sm text-red-600 hover:text-red-800"
                >
                  Auswahl zurücksetzen
                </button>
              )}
            </div>

            {/* Category Filter Bubbles */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-secondary mb-2">
                Kategorien filtern:
              </label>
              <div className="flex flex-wrap gap-2">
                {categories.map((category) => {
                  const isSelected = selectedCategories.has(category.id)
                  return (
                    <button
                      key={category.id}
                      onClick={() => toggleCategory(category.id)}
                      className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all flex items-center gap-1 border-2 ${
                        isSelected 
                          ? getCategoryColor(category.id) + ' shadow-md scale-105'
                          : 'bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100'
                      }`}
                    >
                      <span>{category.icon}</span>
                      <span>{category.name}</span>
                      {isSelected && <span className="ml-1">✓</span>}
                    </button>
                  )
                })}
              </div>
            </div>

            {selectedSkills.size > 0 && (
              <div className="mb-4 p-3 bg-blue-50 rounded-lg">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm font-medium text-blue-800">
                    Ausgewählte Skills ({selectedSkills.size}):
                  </span>
                  <button
                    onClick={() => setSelectedSkills(new Set())}
                    className="text-xs text-blue-600 hover:text-blue-800"
                  >
                    Alle abwählen
                  </button>
                </div>
                <div className="flex flex-wrap gap-2">
                  {Array.from(selectedSkills).map(skillId => {
                    const skill = allSkills.find(s => s.id === skillId)
                    return (
                      <button
                        key={skillId}
                        onClick={() => toggleSkill(skillId)}
                        className="px-3 py-1 bg-blue-600 text-white rounded-full text-sm hover:bg-blue-700"
                      >
                        {skill?.name || skillId} ×
                      </button>
                    )
                  })}
                </div>
              </div>
            )}

            {selectedCategories.size === 0 ? (
              <div className="text-center py-8 bg-gray-50 rounded-lg">
                <p className="text-tertiary mb-2">
                  Wählen Sie zuerst eine Kategorie aus
                </p>
                <p className="text-sm text-tertiary">
                  Die verfügbaren Skills werden dann hier angezeigt
                </p>
              </div>
            ) : (
              <>
                <div className="flex flex-wrap gap-2">
                  {getFilteredSkills().slice(0, 30).map(skill => {
                    const isSelected = selectedSkills.has(skill.id)
                    const isAssigned = assignedSkills.has(skill.id)
                    
                    // Calculate size based on count
                    const size = skill.count > 15 ? 'text-base' : 
                               skill.count > 8 ? 'text-sm' : 
                               'text-xs'
                    
                    return (
                      <button
                        key={skill.id}
                        onClick={() => toggleSkill(skill.id)}
                        className={`px-3 py-1.5 rounded-full font-medium transition-all ${size} ${
                          isSelected
                            ? 'bg-blue-600 text-white shadow-md scale-105'
                            : isAssigned
                            ? 'bg-green-100 text-green-800 border border-green-300'
                            : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                        }`}
                      >
                        {skill.name}
                        <span className="ml-1 opacity-60">×{skill.count}</span>
                        {isSelected && ' ✓'}
                      </button>
                    )
                  })}
                </div>

                {getFilteredSkills().length === 0 && (
                  <p className="text-center text-tertiary py-4">
                    Keine Skills in den gewählten Kategorien gefunden
                  </p>
                )}

                {getFilteredSkills().length > 30 && (
                  <p className="text-xs text-tertiary mt-2">
                    Zeige {30} von {getFilteredSkills().length} Skills
                  </p>
                )}
              </>
            )}

          </div>

          {/* Filtered Employees */}
          <div className="card">
            <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">
              {selectedSkills.size > 0 || searchTerm || selectedDepartment || selectedPosition
                ? `Gefilterte Mitarbeitende (${filteredEmployees.length})`
                : `Mitarbeitende`
              }
            </h2>

            <div className="space-y-2 max-h-[500px] overflow-y-auto">
              {(!searchTerm && !selectedDepartment && !selectedPosition && selectedSkills.size === 0) ? (
                <div className="text-center py-12 bg-gray-50 rounded-lg">
                  <p className="text-tertiary mb-2">
                    Nutzen Sie die Filter oder wählen Sie Skills aus
                  </p>
                  <p className="text-sm text-tertiary">
                    Die passenden Mitarbeitenden werden dann hier angezeigt
                  </p>
                </div>
              ) : filteredEmployees.length === 0 ? (
                <p className="text-center text-tertiary py-8">
                  Keine passenden Mitarbeitenden gefunden
                </p>
              ) : (
                filteredEmployees.map((employee: any) => {
                  const isAssigned = teamPositions.some(p => p.assignedEmployeeId === employee.id)
                  const matchScore = employee.matchScore || 0
                  
                  return (
                    <div
                      key={employee.id}
                      className={`p-4 rounded-lg border transition-all ${
                        isAssigned
                          ? 'bg-gray-50 border-gray-300 opacity-60'
                          : assigningEmployee === employee.id
                          ? 'bg-blue-50 border-blue-400 shadow-lg'
                          : 'bg-white border-gray-200 hover:border-blue-300 hover:shadow-md'
                      }`}
                    >
                      <div className="flex items-start gap-3">
                        {/* Photo */}
                        <div className="w-12 h-12 rounded-full bg-gray-200 overflow-hidden flex-shrink-0">
                          {employee.photo ? (
                            <img
                              src={toPublic(employee.photo)}
                              alt={employee.firstName}
                              className="w-full h-full object-cover"
                            />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center text-sm font-medium text-gray-600">
                              {employee.firstName?.[0]}{employee.lastName?.[0]}
                            </div>
                          )}
                        </div>

                        {/* Info */}
                        <div className="flex-1">
                          <div className="flex items-start justify-between">
                            <div>
                              <div className="font-medium text-primary">
                                {employee.firstName} {employee.lastName}
                              </div>
                              <div className="text-sm text-tertiary">
                                {employee.position}
                                {employee.officialTitle ? ` • ${employee.officialTitle}` : ''}
                                {` • ${employee.department}`}
                              </div>
                            </div>

                            {/* Match Score */}
                            {matchScore > 0 && (
                              <div className={`text-lg font-bold ${
                                matchScore >= 80 ? 'text-green-600' :
                                matchScore >= 50 ? 'text-yellow-600' :
                                'text-orange-600'
                              }`}>
                                {matchScore}% Match
                              </div>
                            )}
                          </div>

                          {/* Skills */}
                          <div className="flex flex-wrap gap-1 mt-2">
                            {/* Regular skills */}
                            {employee.skills?.slice(0, 5).map((skill: any) => {
                              const level = parseInt(skill.level) || 0
                              const isSelected = selectedSkills.has(skill.id)
                              
                              return (
                                <span
                                  key={skill.id}
                                  className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs ${
                                    isSelected
                                      ? 'bg-green-100 text-green-800 font-medium'
                                      : 'bg-gray-100 text-gray-600'
                                  }`}
                                >
                                  {level >= 7 ? '★' : level >= 4 ? '■' : '●'}
                                  {skill.name}
                                </span>
                              )
                            })}
                            
                            {/* Language skills */}
                            {employee.languages?.slice(0, 3).map((lang: any) => {
                              // Map language names to match skill IDs
                              const languageMap: Record<string, string> = {
                                'Deutsch': 'de',
                                'Englisch': 'en',
                                'Französisch': 'fr',
                                'Spanisch': 'es',
                                'Italienisch': 'it',
                                'Russisch': 'ru',
                                'Arabisch': 'ar',
                                'Türkisch': 'tr',
                                'Polnisch': 'pl',
                                'Chinesisch': 'zh',
                                'Farsi/Persisch': 'fa'
                              }
                              
                              const langId = languageMap[lang.code] || lang.code
                              const isSelected = selectedSkills.has(langId)
                              
                              return (
                                <span
                                  key={lang.code}
                                  className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs ${
                                    isSelected
                                      ? 'bg-green-100 text-green-800 font-medium'
                                      : 'bg-gray-100 text-gray-600'
                                  }`}
                                >
                                  🌐 {lang.code}
                                </span>
                              )
                            })}
                            
                            {((employee.skills?.length || 0) + (employee.languages?.length || 0)) > 8 && (
                              <span className="text-xs text-tertiary">
                                +{(employee.skills?.length || 0) + (employee.languages?.length || 0) - 8}
                              </span>
                            )}
                          </div>
                        </div>

                        {/* Action Button */}
                        <div className="flex-shrink-0">
                          {isAssigned ? (
                            <span className="inline-block px-3 py-1 bg-gray-200 text-gray-600 rounded text-sm">
                              Bereits zugewiesen
                            </span>
                          ) : assigningEmployee === employee.id ? (
                            <button
                              onClick={() => setAssigningEmployee(null)}
                              className="px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700"
                            >
                              Abbrechen
                            </button>
                          ) : (
                            <button
                              onClick={() => startAssignment(employee.id)}
                              className="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700"
                            >
                              Zuweisen →
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                  )
                })
              )}
            </div>
          </div>
        </div>

        {/* Right Sidebar - Team Overview */}
        <div className="lg:col-span-1">
          <div className="card sticky top-4">
            {/* Team Header */}
            <div className="mb-4">
              <input
                type="text"
                value={teamName}
                onChange={(e) => setTeamName(e.target.value)}
                className="text-title-card font-semibold text-primary bg-transparent border-b-2 border-transparent hover:border-gray-300 focus:border-blue-500 transition-colors outline-none w-full"
                placeholder="Team-Name..."
              />
              <div className="flex items-center justify-between mt-2">
                <span className="text-sm text-tertiary">
                  {teamPositions.length} Positionen
                </span>
                <span className={`text-sm font-medium ${
                  getTeamCompleteness() === 100 ? 'text-green-600' :
                  getTeamCompleteness() > 50 ? 'text-yellow-600' :
                  'text-gray-600'
                }`}>
                  {getTeamCompleteness()}% besetzt
                </span>
              </div>
            </div>

            {/* Positions */}
            <div className="space-y-3 mb-4">
              {teamPositions.length === 0 ? (
                <div className="text-center py-8 border-2 border-dashed border-gray-300 rounded-lg">
                  <p className="text-tertiary text-sm">
                    Noch keine Positionen definiert
                  </p>
                  <button
                    onClick={addTeamPosition}
                    className="mt-2 text-sm text-blue-600 hover:text-blue-800"
                  >
                    Erste Position hinzufügen
                  </button>
                </div>
              ) : (
                teamPositions.map(position => {
                  const assignedEmployee = position.assignedEmployeeId
                    ? getEmployeeById(position.assignedEmployeeId)
                    : null
                  const isTarget = assigningEmployee && !position.assignedEmployeeId

                  return (
                    <div
                      key={position.id}
                      className={`p-3 rounded-lg border-2 transition-all ${
                        isTarget
                          ? 'border-blue-400 bg-blue-50 shadow-lg'
                          : 'border-gray-200 bg-white'
                      }`}
                    >
                      {/* Position Title */}
                      <div className="flex items-center justify-between mb-2">
                        <input
                          type="text"
                          value={position.title}
                          onChange={(e) => updatePositionTitle(position.id, e.target.value)}
                          className="font-medium text-primary bg-transparent border-b border-transparent hover:border-gray-300 focus:border-blue-500 transition-colors outline-none flex-1"
                          placeholder="Positionsbezeichnung..."
                        />
                        <button
                          onClick={() => removeTeamPosition(position.id)}
                          className="text-gray-400 hover:text-red-500 ml-2"
                        >
                          ×
                        </button>
                      </div>

                      {/* Assigned Employee or Assignment Button */}
                      {assignedEmployee ? (
                        <div className="flex items-center gap-2">
                          <div className="w-8 h-8 rounded-full bg-gray-200 overflow-hidden flex-shrink-0">
                            {assignedEmployee.photo ? (
                              <img
                                src={toPublic(assignedEmployee.photo)}
                                alt={assignedEmployee.firstName}
                                className="w-full h-full object-cover"
                              />
                            ) : (
                              <div className="w-full h-full flex items-center justify-center text-xs font-medium text-gray-600">
                                {assignedEmployee.firstName?.[0]}{assignedEmployee.lastName?.[0]}
                              </div>
                            )}
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-medium text-gray-900 truncate">
                              {assignedEmployee.firstName} {assignedEmployee.lastName}
                            </div>
                            <div className="text-xs text-gray-600">
                              {assignedEmployee.position}
                            </div>
                          </div>
                          <button
                            onClick={() => unassignEmployee(position.id)}
                            className="text-xs text-red-600 hover:text-red-800"
                          >
                            Entfernen
                          </button>
                        </div>
                      ) : isTarget ? (
                        <button
                          onClick={() => assignEmployee(position.id)}
                          className="w-full py-2 bg-blue-600 text-white rounded text-sm font-medium hover:bg-blue-700 animate-pulse"
                        >
                          Hier zuweisen
                        </button>
                      ) : (
                        <div className="py-2 text-center text-xs text-gray-400">
                          Wählen Sie eine Person aus
                        </div>
                      )}
                    </div>
                  )
                })
              )}
            </div>

            {/* Add Position Button */}
            <button
              onClick={addTeamPosition}
              className="w-full py-2 border-2 border-dashed border-gray-300 rounded-lg text-sm text-gray-600 hover:border-gray-400 hover:text-gray-800 transition-colors"
            >
              + Neue Position
            </button>

            {/* Actions */}
            {teamPositions.length > 0 && (
              <div className="mt-6 pt-4 border-t border-gray-200 space-y-2">
                <button className="w-full btn-secondary text-sm">
                  Als Vorlage speichern
                </button>
                <button className="w-full btn-primary text-sm">
                  Team exportieren
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Assignment Helper Message */}
      {assigningEmployee && (
        <div className="fixed bottom-4 left-1/2 -translate-x-1/2 bg-blue-600 text-white px-6 py-3 rounded-lg shadow-xl z-50 animate-bounce">
          <div className="flex items-center gap-3">
            <span className="font-medium">
              Wählen Sie eine Position aus der Team-Übersicht →
            </span>
            <button
              onClick={() => setAssigningEmployee(null)}
              className="text-white/80 hover:text-white"
            >
              Abbrechen
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
