import { Settings, Grid, List, BarChart3, Calendar } 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 { CustomVariantBlockProps } from '../types'

type ViewMode = 'grid' | 'list' | 'chart' | 'calendar'
type ColorTheme = 'blue' | 'green' | 'purple' | 'orange'
type DataDensity = 'minimal' | 'normal' | 'detailed'

/**
 * Кастомный вариант табеля - настраиваемая пользователем конфигурация
 * 
 * Особенности:
 * - Переключение между разными режимами отображения
 * - Настройка цветовых схем
 * - Изменение плотности данных
 * - Персонализированные фильтры и группировки
 * - Сохранение пользовательских предпочтений
 */
export const CustomVariantBlock = memo<CustomVariantBlockProps>(function CustomVariantBlock({
  employee,
  calendarData,
  stats,
  utils,
  selectedMonth,
  selectedYear,
}) {
  const [viewMode, setViewMode] = useState<ViewMode>('grid')
  const [colorTheme, setColorTheme] = useState<ColorTheme>('blue')
  const [dataDensity, setDataDensity] = useState<DataDensity>('normal')
  const [showSettings, setShowSettings] = useState(false)

  const monthName = utils.getMonthName(selectedMonth)
  const daysInMonth = utils.getDaysInMonth(selectedMonth, selectedYear)

  const getThemeColors = (theme: ColorTheme) => {
    const themes = {
      blue: {
        primary: 'from-blue-500 to-indigo-600',
        secondary: 'from-blue-400 to-blue-500',
        accent: 'text-blue-400',
        bg: 'bg-blue-500/10',
        border: 'border-blue-500/30',
      },
      green: {
        primary: 'from-green-500 to-emerald-600',
        secondary: 'from-green-400 to-green-500',
        accent: 'text-green-400',
        bg: 'bg-green-500/10',
        border: 'border-green-500/30',
      },
      purple: {
        primary: 'from-purple-500 to-violet-600',
        secondary: 'from-purple-400 to-purple-500',
        accent: 'text-purple-400',
        bg: 'bg-purple-500/10',
        border: 'border-purple-500/30',
      },
      orange: {
        primary: 'from-orange-500 to-red-600',
        secondary: 'from-orange-400 to-orange-500',
        accent: 'text-orange-400',
        bg: 'bg-orange-500/10',
        border: 'border-orange-500/30',
      },
    }
    return themes[theme]
  }

  const theme = getThemeColors(colorTheme)

  const renderGridView = () => {
    const weeks: (number | null)[][] = []
    let currentWeek: (number | null)[] = []
    const firstDayOfMonth = utils.getFirstDayOfMonth(selectedMonth, selectedYear)
    
    // Заполняем пустые дни в начале месяца
    for (let i = 0; i < firstDayOfMonth; i++) {
      currentWeek.push(null)
    }
    
    // Заполняем дни месяца
    for (let day = 1; day <= daysInMonth; day++) {
      if (currentWeek.length === 7) {
        weeks.push(currentWeek)
        currentWeek = []
      }
      currentWeek.push(day)
    }
    
    // Заполняем оставшиеся дни
    while (currentWeek.length < 7) {
      currentWeek.push(null)
    }
    weeks.push(currentWeek)

    return (
      <div className="space-y-2">
        <div className="grid grid-cols-7 gap-2 mb-4">
          {['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'].map(day => (
            <div key={day} className="text-center text-white/70 font-medium py-2">
              {day}
            </div>
          ))}
        </div>
        
        {weeks.map((week, weekIndex) => (
          <div key={weekIndex} className="grid grid-cols-7 gap-2">
            {week.map((day, dayIndex) => {
              if (!day) return <div key={dayIndex} className="h-16" />
              
              const dayData = calendarData.find(d => d.day === day)
              
              return (
                <div 
                  key={day} 
                  className={`
                    relative h-16 rounded-lg border-2 transition-all duration-300 cursor-pointer
                    hover:scale-105 group ${theme.bg} ${theme.border}
                    ${dayData ? 'border-opacity-50' : 'border-opacity-20'}
                  `}
                >
                  <div className="absolute top-1 left-2 text-sm font-bold text-white">
                    {day}
                  </div>
                  
                  {dayData && dataDensity !== 'minimal' && (
                    <>
                      <div className="absolute top-1 right-2 text-xs text-white/80">
                        {dayData.hours}ч
                      </div>
                      
                      {dataDensity === 'detailed' && (
                        <>
                          <div className="absolute bottom-1 left-2 text-xs text-white/60">
                            {dayData.tasks} задач
                          </div>
                          
                          {dayData.efficiency !== null && (
                            <div className="absolute bottom-1 right-2 text-xs text-white/60">
                              {dayData.efficiency}%
                            </div>
                          )}
                        </>
                      )}
                    </>
                  )}
                </div>
              )
            })}
          </div>
        ))}
      </div>
    )
  }

  const renderListView = () => (
    <div className="space-y-2">
      {calendarData.map(day => (
        <div 
          key={day.day} 
          className={`
            flex items-center justify-between p-4 rounded-lg transition-all duration-300
            hover:scale-[1.02] ${theme.bg} ${theme.border} border
          `}
        >
          <div className="flex items-center space-x-4">
            <div className="w-8 h-8 bg-gradient-to-r ${theme.secondary} rounded-full flex items-center justify-center text-white font-bold">
              {day.day}
            </div>
            <div>
              <div className="text-white font-medium">
                День {day.day} • {utils.formatHours(day.hours)}
              </div>
              {dataDensity !== 'minimal' && (
                <div className="text-white/60 text-sm">
                  {day.tasks} задач • {day.efficiency}% эффективность
                  {day.overtime > 0 && ` • +${day.overtime}ч переработка`}
                </div>
              )}
            </div>
          </div>
          
          <div className={`text-lg font-bold ${theme.accent}`}>
            {day.hours + day.overtime}ч
          </div>
        </div>
      ))}
    </div>
  )

  const renderChartView = () => {
    const maxHours = Math.max(...calendarData.map(d => d.hours + d.overtime))
    
    return (
      <div className="space-y-4">
        <div className="grid grid-cols-1 gap-2">
          {calendarData.map(day => {
            const totalHours = day.hours + day.overtime
            const percentage = maxHours > 0 ? (totalHours / maxHours) * 100 : 0
            
            return (
              <div key={day.day} className="flex items-center space-x-4">
                <div className="w-12 text-white/70 text-sm">
                  День {day.day}
                </div>
                <div className="flex-1 relative">
                  <div className="h-8 bg-white/10 rounded-lg overflow-hidden">
                    <div 
                      className={`h-full bg-gradient-to-r ${theme.primary} transition-all duration-500`}
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                  <div className="absolute inset-0 flex items-center px-3 text-white text-sm">
                    {totalHours}ч
                    {dataDensity === 'detailed' && ` • ${day.tasks} задач • ${day.efficiency}%`}
                  </div>
                </div>
              </div>
            )
          })}
        </div>
      </div>
    )
  }

  const renderCalendarView = () => (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      {calendarData.filter(d => d.hours > 0).map(day => (
        <div 
          key={day.day} 
          className={`
            p-4 rounded-lg ${theme.bg} ${theme.border} border transition-all duration-300
            hover:scale-105 cursor-pointer
          `}
        >
          <div className="flex items-center justify-between mb-3">
            <div className="text-lg font-bold text-white">День {day.day}</div>
            <div className={`text-sm ${theme.accent} font-medium`}>
              {utils.formatHours(day.hours + day.overtime)}
            </div>
          </div>
          
          {dataDensity !== 'minimal' && (
            <div className="space-y-2 text-sm text-white/70">
              <div>Статус: {day.status}</div>
              <div>Задач выполнено: {day.tasks}</div>
              <div>Эффективность: {day.efficiency}%</div>
              {day.overtime > 0 && (
                <div className="text-orange-400">Переработка: +{day.overtime}ч</div>
              )}
            </div>
          )}
        </div>
      ))}
    </div>
  )

  return (
    <div className="custom-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">
              🎨 {employee.name} - Кастомный вид
            </h2>
            <p className="text-white/70">
              {employee.position} • {monthName} {selectedYear}
            </p>
          </div>
          
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowSettings(!showSettings)}
            className="text-white border-white/30 hover:bg-white/10"
          >
            <Settings className="w-4 h-4 mr-2" />
            Настройки
          </Button>
        </div>

        {/* Панель настроек */}
        {showSettings && (
          <div className={`p-4 rounded-lg ${theme.bg} ${theme.border} border space-y-4`}>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-white/70 text-sm mb-2">Режим отображения</label>
                <Select value={viewMode} onValueChange={(value: ViewMode) => setViewMode(value)}>
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-gray-900 border-white/20">
                    <SelectItem value="grid">
                      <div className="flex items-center space-x-2">
                        <Grid className="w-4 h-4" />
                        <span>Календарная сетка</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="list">
                      <div className="flex items-center space-x-2">
                        <List className="w-4 h-4" />
                        <span>Список</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="chart">
                      <div className="flex items-center space-x-2">
                        <BarChart3 className="w-4 h-4" />
                        <span>Диаграмма</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="calendar">
                      <div className="flex items-center space-x-2">
                        <Calendar className="w-4 h-4" />
                        <span>Карточки</span>
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <label className="block text-white/70 text-sm mb-2">Цветовая тема</label>
                <Select value={colorTheme} onValueChange={(value: ColorTheme) => setColorTheme(value)}>
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-gray-900 border-white/20">
                    <SelectItem value="blue">
                      <div className="flex items-center space-x-2">
                        <div className="w-4 h-4 bg-blue-500 rounded" />
                        <span>Синяя</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="green">
                      <div className="flex items-center space-x-2">
                        <div className="w-4 h-4 bg-green-500 rounded" />
                        <span>Зеленая</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="purple">
                      <div className="flex items-center space-x-2">
                        <div className="w-4 h-4 bg-purple-500 rounded" />
                        <span>Фиолетовая</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="orange">
                      <div className="flex items-center space-x-2">
                        <div className="w-4 h-4 bg-orange-500 rounded" />
                        <span>Оранжевая</span>
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <label className="block text-white/70 text-sm mb-2">Детализация</label>
                <Select value={dataDensity} onValueChange={(value: DataDensity) => setDataDensity(value)}>
                  <SelectTrigger className="bg-white/10 border-white/20 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-gray-900 border-white/20">
                    <SelectItem value="minimal">Минимальная</SelectItem>
                    <SelectItem value="normal">Обычная</SelectItem>
                    <SelectItem value="detailed">Подробная</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>
        )}

        {/* Быстрая статистика */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
          <div className="text-center">
            <div className={`text-2xl font-bold ${theme.accent}`}>{stats.totalHours}ч</div>
            <div className="text-white/60 text-sm">Всего часов</div>
          </div>
          <div className="text-center">
            <div className={`text-2xl font-bold ${theme.accent}`}>{stats.workDays}</div>
            <div className="text-white/60 text-sm">Рабочих дней</div>
          </div>
          <div className="text-center">
            <div className={`text-2xl font-bold ${theme.accent}`}>{stats.efficiency}%</div>
            <div className="text-white/60 text-sm">Эффективность</div>
          </div>
          <div className="text-center">
            <div className={`text-2xl font-bold ${theme.accent}`}>{stats.completedTasks}</div>
            <div className="text-white/60 text-sm">Задач</div>
          </div>
        </div>
      </div>

      {/* Основной контент */}
      <div className="glass-card p-6">
        <div className="flex items-center space-x-3 mb-6">
          {viewMode === 'grid' && <Grid className={`w-5 h-5 ${theme.accent}`} />}
          {viewMode === 'list' && <List className={`w-5 h-5 ${theme.accent}`} />}
          {viewMode === 'chart' && <BarChart3 className={`w-5 h-5 ${theme.accent}`} />}
          {viewMode === 'calendar' && <Calendar className={`w-5 h-5 ${theme.accent}`} />}
          <h3 className="text-xl font-bold text-white">
            {viewMode === 'grid' && 'Календарная сетка'}
            {viewMode === 'list' && 'Список рабочих дней'}
            {viewMode === 'chart' && 'Диаграмма нагрузки'}
            {viewMode === 'calendar' && 'Карточки дней'}
          </h3>
        </div>

        {viewMode === 'grid' && renderGridView()}
        {viewMode === 'list' && renderListView()}
        {viewMode === 'chart' && renderChartView()}
        {viewMode === 'calendar' && renderCalendarView()}
      </div>
    </div>
  )
})

CustomVariantBlock.displayName = 'CustomVariantBlock'