import { TrendingUp, TrendingDown, User, Award, Clock, BarChart3, Filter } from 'lucide-react'
import { memo, useState } from 'react'

import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

import type { MultiEmployeeVariantBlockProps } from '../types'

type SortBy = 'hours' | 'efficiency' | 'tasks' | 'name'
type FilterBy = 'all' | 'high-performers' | 'underperformers' | 'overtime-workers'

/**
 * Мульти-сотрудник вариант табеля - сравнение нескольких сотрудников
 * 
 * Особенности:
 * - Сравнительные таблицы и графики
 * - Рейтинги и сортировки
 * - Фильтры по показателям
 * - Командная аналитика
 * - Визуализация performance разных сотрудников
 */
export const MultiEmployeeVariantBlock = memo<MultiEmployeeVariantBlockProps>(function MultiEmployeeVariantBlock({
  employees,
  employeeStats,
  selectedMonth,
  selectedYear,
  utils,
}) {
  const [sortBy, setSortBy] = useState<SortBy>('hours')
  const [filterBy, setFilterBy] = useState<FilterBy>('all')
  const [viewMode, setViewMode] = useState<'table' | 'cards' | 'chart'>('cards')

  const monthName = utils.getMonthName(selectedMonth)

  // Фильтрация сотрудников
  const filteredEmployees = employees.filter(employee => {
    const stats = employeeStats[employee.id]
    if (!stats) return false

    switch (filterBy) {
      case 'high-performers':
        return stats.efficiency >= 85
      case 'underperformers':
        return stats.efficiency < 70
      case 'overtime-workers':
        return stats.overtime > 10
      default:
        return true
    }
  })

  // Сортировка сотрудников
  const sortedEmployees = [...filteredEmployees].sort((a, b) => {
    const statsA = employeeStats[a.id]
    const statsB = employeeStats[b.id]
    
    if (!statsA || !statsB) return 0

    switch (sortBy) {
      case 'hours':
        return statsB.totalHours - statsA.totalHours
      case 'efficiency':
        return statsB.efficiency - statsA.efficiency
      case 'tasks':
        return statsB.completedTasks - statsA.completedTasks
      case 'name':
        return a.name.localeCompare(b.name)
      default:
        return 0
    }
  })

  // Общая статистика команды
  const teamStats = employees.reduce(
    (acc, employee) => {
      const stats = employeeStats[employee.id]
      if (!stats) return acc

      return {
        totalHours: acc.totalHours + stats.totalHours,
        totalTasks: acc.totalTasks + stats.completedTasks,
        totalOvertime: acc.totalOvertime + stats.overtime,
        avgEfficiency: acc.avgEfficiency + stats.efficiency,
        employeeCount: acc.employeeCount + 1,
      }
    },
    { totalHours: 0, totalTasks: 0, totalOvertime: 0, avgEfficiency: 0, employeeCount: 0 },
  )

  if (teamStats.employeeCount > 0) {
    teamStats.avgEfficiency = Math.round(teamStats.avgEfficiency / teamStats.employeeCount)
  }

  const getPerformanceColor = (efficiency: number) => {
    if (efficiency >= 90) return 'text-green-400 bg-green-500/20'
    if (efficiency >= 75) return 'text-blue-400 bg-blue-500/20'
    if (efficiency >= 60) return 'text-yellow-400 bg-yellow-500/20'
    return 'text-red-400 bg-red-500/20'
  }

  const getEfficiencyIcon = (efficiency: number) => {
    if (efficiency >= 85) return <TrendingUp className="w-4 h-4 text-green-400" />
    if (efficiency < 70) return <TrendingDown className="w-4 h-4 text-red-400" />
    return <BarChart3 className="w-4 h-4 text-blue-400" />
  }

  const renderTableView = () => (
    <div className="overflow-x-auto">
      <table className="w-full">
        <thead>
          <tr className="border-b border-white/20">
            <th className="text-left p-3 text-white/70">Сотрудник</th>
            <th className="text-center p-3 text-white/70">Часы</th>
            <th className="text-center p-3 text-white/70">Эффективность</th>
            <th className="text-center p-3 text-white/70">Задачи</th>
            <th className="text-center p-3 text-white/70">Переработки</th>
            <th className="text-center p-3 text-white/70">Рейтинг</th>
          </tr>
        </thead>
        <tbody>
          {sortedEmployees.map((employee, index) => {
            const stats = employeeStats[employee.id]
            if (!stats) return null

            return (
              <tr key={employee.id} className="border-b border-white/10 hover:bg-white/5">
                <td className="p-3">
                  <div className="flex items-center space-x-3">
                    <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                      <User className="w-4 h-4 text-white" />
                    </div>
                    <div>
                      <div className="text-white font-medium">{employee.name}</div>
                      <div className="text-white/60 text-sm">{employee.position}</div>
                    </div>
                  </div>
                </td>
                <td className="p-3 text-center">
                  <div className="text-white font-bold">{stats.totalHours}ч</div>
                  <div className="text-white/60 text-sm">{stats.workDays} дней</div>
                </td>
                <td className="p-3 text-center">
                  <div className={`inline-flex items-center space-x-1 px-2 py-1 rounded ${getPerformanceColor(stats.efficiency)}`}>
                    {getEfficiencyIcon(stats.efficiency)}
                    <span className="font-bold">{stats.efficiency}%</span>
                  </div>
                </td>
                <td className="p-3 text-center">
                  <div className="text-white font-bold">{stats.completedTasks}</div>
                  <div className="text-white/60 text-sm">задач</div>
                </td>
                <td className="p-3 text-center">
                  <div className={`text-white font-bold ${stats.overtime > 20 ? 'text-red-400' : stats.overtime > 10 ? 'text-yellow-400' : 'text-green-400'}`}>
                    {stats.overtime}ч
                  </div>
                </td>
                <td className="p-3 text-center">
                  <div className="flex items-center justify-center space-x-1">
                    {index === 0 && <Award className="w-4 h-4 text-yellow-400" />}
                    <span className="text-white font-bold">#{index + 1}</span>
                  </div>
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
  )

  const renderCardsView = () => (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      {sortedEmployees.map((employee, index) => {
        const stats = employeeStats[employee.id]
        if (!stats) return null

        return (
          <div key={employee.id} className="glass-card p-6 relative overflow-hidden group hover:scale-105 transition-all duration-300">
            {/* Рейтинговая позиция */}
            {index < 3 && (
              <div className="absolute top-4 right-4">
                {index === 0 && <div className="text-2xl">🥇</div>}
                {index === 1 && <div className="text-2xl">🥈</div>}
                {index === 2 && <div className="text-2xl">🥉</div>}
              </div>
            )}

            {/* Информация о сотруднике */}
            <div className="flex items-center space-x-3 mb-4">
              <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                <User className="w-6 h-6 text-white" />
              </div>
              <div>
                <h4 className="text-lg font-bold text-white">{employee.name}</h4>
                <p className="text-white/60 text-sm">{employee.position}</p>
                <p className="text-white/50 text-xs">{employee.department}</p>
              </div>
            </div>

            {/* Статистика */}
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-white/70 flex items-center space-x-1">
                  <Clock className="w-4 h-4" />
                  <span>Время:</span>
                </span>
                <span className="text-white font-bold">{stats.totalHours}ч</span>
              </div>

              <div className="flex justify-between items-center">
                <span className="text-white/70">Эффективность:</span>
                <span className={`font-bold ${getPerformanceColor(stats.efficiency).split(' ')[0]}`}>
                  {stats.efficiency}%
                </span>
              </div>

              <div className="flex justify-between items-center">
                <span className="text-white/70">Задач:</span>
                <span className="text-white font-bold">{stats.completedTasks}</span>
              </div>

              <div className="flex justify-between items-center">
                <span className="text-white/70">Переработки:</span>
                <span className={`font-bold ${stats.overtime > 20 ? 'text-red-400' : stats.overtime > 10 ? 'text-yellow-400' : 'text-green-400'}`}>
                  {stats.overtime}ч
                </span>
              </div>
            </div>

            {/* Прогресс бар */}
            <div className="mt-4">
              <div className="flex justify-between items-center mb-2">
                <span className="text-white/60 text-sm">Прогресс:</span>
                <span className="text-white/60 text-sm">{Math.round((stats.totalHours / 160) * 100)}%</span>
              </div>
              <div className="w-full bg-white/10 rounded-full h-2">
                <div 
                  className="bg-gradient-to-r from-blue-500 to-purple-600 h-2 rounded-full transition-all duration-500"
                  style={{ width: `${Math.min((stats.totalHours / 160) * 100, 100)}%` }}
                />
              </div>
            </div>
          </div>
        )
      })}
    </div>
  )

  const renderChartView = () => {
    const maxHours = Math.max(...sortedEmployees.map(emp => employeeStats[emp.id]?.totalHours || 0))
    
    return (
      <div className="space-y-4">
        <div className="grid grid-cols-1 gap-3">
          {sortedEmployees.map((employee) => {
            const stats = employeeStats[employee.id]
            if (!stats) return null

            const percentage = maxHours > 0 ? (stats.totalHours / maxHours) * 100 : 0
            
            return (
              <div key={employee.id} className="flex items-center space-x-4">
                <div className="w-32 flex-shrink-0">
                  <div className="text-white font-medium truncate">{employee.name}</div>
                  <div className="text-white/60 text-sm">{employee.position}</div>
                </div>
                
                <div className="flex-1 relative">
                  <div className="h-12 bg-white/10 rounded-lg overflow-hidden">
                    <div 
                      className={`h-full bg-gradient-to-r transition-all duration-500 ${getPerformanceColor(stats.efficiency).includes('green') ? 'from-green-500 to-green-600' :
                        getPerformanceColor(stats.efficiency).includes('blue') ? 'from-blue-500 to-blue-600' :
                        getPerformanceColor(stats.efficiency).includes('yellow') ? 'from-yellow-500 to-yellow-600' :
                        'from-red-500 to-red-600'}`}
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                  <div className="absolute inset-0 flex items-center justify-between px-3">
                    <span className="text-white text-sm font-medium">
                      {stats.totalHours}ч • {stats.efficiency}%
                    </span>
                    <span className="text-white/70 text-sm">
                      {stats.completedTasks} задач
                    </span>
                  </div>
                </div>
              </div>
            )
          })}
        </div>
      </div>
    )
  }

  return (
    <div className="multi-employee-variant">
      {/* Заголовок и командная статистика */}
      <div className="glass-card p-6 mb-8">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-2xl font-bold text-white mb-1">
              👥 Команда - {monthName} {selectedYear}
            </h2>
            <p className="text-white/70">
              Сравнительная аналитика {teamStats.employeeCount}{' '}
            сотрудников
            </p>
          </div>
        </div>

        {/* Командная статистика */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-6 mb-6">
          <div className="text-center">
            <div className="w-16 h-16 mx-auto mb-3 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center">
              <Clock className="w-8 h-8 text-white" />
            </div>
            <div className="text-2xl font-bold text-blue-400">{teamStats.totalHours}ч</div>
            <div className="text-white/60 text-sm">Общее время команды</div>
          </div>

          <div className="text-center">
            <div className="w-16 h-16 mx-auto mb-3 bg-gradient-to-br from-green-500 to-green-600 rounded-full flex items-center justify-center">
              <BarChart3 className="w-8 h-8 text-white" />
            </div>
            <div className="text-2xl font-bold text-green-400">{teamStats.avgEfficiency}%</div>
            <div className="text-white/60 text-sm">Средняя эффективность</div>
          </div>

          <div className="text-center">
            <div className="w-16 h-16 mx-auto mb-3 bg-gradient-to-br from-purple-500 to-purple-600 rounded-full flex items-center justify-center">
              <Award className="w-8 h-8 text-white" />
            </div>
            <div className="text-2xl font-bold text-purple-400">{teamStats.totalTasks}</div>
            <div className="text-white/60 text-sm">Задач выполнено</div>
          </div>

          <div className="text-center">
            <div className="w-16 h-16 mx-auto mb-3 bg-gradient-to-br from-orange-500 to-orange-600 rounded-full flex items-center justify-center">
              <TrendingUp className="w-8 h-8 text-white" />
            </div>
            <div className="text-2xl font-bold text-orange-400">{teamStats.totalOvertime}ч</div>
            <div className="text-white/60 text-sm">Переработок</div>
          </div>
        </div>

        {/* Фильтры и сортировка */}
        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center space-x-2">
            <Filter className="w-4 h-4 text-white/60" />
            <Select value={filterBy} onValueChange={(value: FilterBy) => setFilterBy(value)}>
              <SelectTrigger className="w-48 bg-white/10 border-white/20 text-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="bg-gray-900 border-white/20">
                <SelectItem value="all">Все сотрудники</SelectItem>
                <SelectItem value="high-performers">Высокие результаты (85%+)</SelectItem>
                <SelectItem value="underperformers">Низкие результаты (&lt;70%)</SelectItem>
                <SelectItem value="overtime-workers">Переработки (10ч+)</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-center space-x-2">
            <span className="text-white/60 text-sm">Сортировка:</span>
            <Select value={sortBy} onValueChange={(value: SortBy) => setSortBy(value)}>
              <SelectTrigger className="w-40 bg-white/10 border-white/20 text-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="bg-gray-900 border-white/20">
                <SelectItem value="hours">По часам</SelectItem>
                <SelectItem value="efficiency">По эффективности</SelectItem>
                <SelectItem value="tasks">По задачам</SelectItem>
                <SelectItem value="name">По имени</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-center space-x-2">
            <span className="text-white/60 text-sm">Вид:</span>
            <div className="flex space-x-1">
              <Button
                variant={viewMode === 'cards' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('cards')}
                className="text-white"
              >
                Карточки
              </Button>
              <Button
                variant={viewMode === 'table' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('table')}
                className="text-white"
              >
                Таблица
              </Button>
              <Button
                variant={viewMode === 'chart' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('chart')}
                className="text-white"
              >
                График
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* Основной контент */}
      <div className="glass-card p-6">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-xl font-bold text-white">
            Результаты сотрудников ({sortedEmployees.length} из {employees.length})
          </h3>
          <div className="text-sm text-white/60">
            Отфильтровано по: {filterBy === 'all' ? 'все' : 
              filterBy === 'high-performers' ? 'высокие результаты' :
              filterBy === 'underperformers' ? 'низкие результаты' : 'переработки'}
          </div>
        </div>

        {viewMode === 'cards' && renderCardsView()}
        {viewMode === 'table' && renderTableView()}
        {viewMode === 'chart' && renderChartView()}
      </div>
    </div>
  )
})

MultiEmployeeVariantBlock.displayName = 'MultiEmployeeVariantBlock'