'use client'

import { Clock, Zap, FileText, Users } from 'lucide-react'
import { useState } from 'react'

import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

interface BulkEditModalProps {
  isOpen: boolean
  onClose: () => void
  dates: Date[]
  employeeName: string
  onSave: (data: { status: string; hoursWorked?: number; overtimeHours?: number; notes?: string }) => void
}

const statusOptions = [
  { value: 'WORK', label: 'Рабочий день', color: 'text-green-400' },
  { value: 'WEEKEND', label: 'Выходной', color: 'text-blue-400' },
  { value: 'VACATION', label: 'Отпуск', color: 'text-blue-400' },
  { value: 'SICK', label: 'Больничный', color: 'text-orange-400' },
  { value: 'ABSENT', label: 'Отсутствие', color: 'text-red-400' },
]

export function BulkEditModal({ isOpen, onClose, dates, employeeName, onSave }: BulkEditModalProps) {
  const [status, setStatus] = useState('WORK')
  const [hoursWorked, setHoursWorked] = useState('8')
  const [overtimeHours, setOvertimeHours] = useState('0')
  const [notes, setNotes] = useState('')

  const handleSave = () => {
    const data = {
      status,
      hoursWorked: status === 'WORK' ? parseFloat(hoursWorked) || 0 : undefined,
      overtimeHours: status === 'WORK' ? parseFloat(overtimeHours) || 0 : undefined,
      notes: notes.trim() || undefined,
    }
    onSave(data)
    onClose()
  }

  const formatDateRange = (dates: Date[]) => {
    if (dates.length === 0) return ''
    if (dates.length === 1) {
      return dates[0].toLocaleDateString('ru-RU', {
        weekday: 'long',
        day: 'numeric',
        month: 'long',
      })
    }

    const sortedDates = [...dates].sort((a, b) => a.getTime() - b.getTime())
    const first = sortedDates[0]
    const last = sortedDates[sortedDates.length - 1]

    return `${first.getDate()} - ${last.getDate()} ${first.toLocaleDateString('ru-RU', { month: 'long' })}`
  }

  const isWorkDay = status === 'WORK'
  const _selectedStatus = statusOptions.find((opt) => opt.value === status)

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="glass-card border-white/10 max-w-md">
        <DialogHeader>
          <DialogTitle className="text-white flex items-center gap-2">
            <Users className="h-5 w-5 text-purple-400" />
            Массовое редактирование
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Информация о выделенных днях */}
          <div className="bg-white/5 rounded-lg p-3 border border-white/10">
            <div className="text-white font-medium">{employeeName}</div>
            <div className="text-white/70 text-sm">
              {formatDateRange(dates)} ({dates.length} {dates.length === 1 ? 'день' : dates.length < 5 ? 'дня' : 'дней'}
              )
            </div>
          </div>

          {/* Статус дня */}
          <div className="space-y-2">
            <Label className="text-white">Статус для всех выбранных дней</Label>
            <Select value={status} onValueChange={setStatus}>
              <SelectTrigger className="glass-secondary border-white/20 text-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="glass-card border-white/10">
                {statusOptions.map((option) => (
                  <SelectItem key={option.value} value={option.value} className={`${option.color} hover:bg-white/10`}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Рабочие часы - только для рабочих дней */}
          {isWorkDay && (
            <>
              <div className="space-y-2">
                <Label className="text-white flex items-center gap-2">
                  <Clock className="h-4 w-4 text-green-400" />
                  Отработано часов (для каждого дня)
                </Label>
                <Input
                  type="number"
                  min="0"
                  max="24"
                  step="0.5"
                  value={hoursWorked}
                  onChange={(e) => setHoursWorked(e.target.value)}
                  className="glass-secondary border-white/20 text-white"
                  placeholder="8"
                />
              </div>

              <div className="space-y-2">
                <Label className="text-white flex items-center gap-2">
                  <Zap className="h-4 w-4 text-yellow-400" />
                  Переработка (часов для каждого дня)
                </Label>
                <Input
                  type="number"
                  min="0"
                  max="12"
                  step="0.5"
                  value={overtimeHours}
                  onChange={(e) => setOvertimeHours(e.target.value)}
                  className="glass-secondary border-white/20 text-white"
                  placeholder="0"
                />
              </div>
            </>
          )}

          {/* Заметки */}
          <div className="space-y-2">
            <Label className="text-white flex items-center gap-2">
              <FileText className="h-4 w-4 text-blue-400" />
              Заметки (для всех дней)
            </Label>
            <Input
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              className="glass-secondary border-white/20 text-white"
              placeholder="Дополнительная информация..."
            />
          </div>

          {/* Предупреждение */}
          <div className="bg-yellow-500/10 border border-yellow-400/30 rounded-lg p-3">
            <p className="text-yellow-200 text-xs">
              ⚠️ Эти настройки будут применены ко всем {dates.length} выбранным дням. Существующие данные будут
              перезаписаны.
            </p>
          </div>

          {/* Кнопки */}
          <div className="flex gap-3 pt-4">
            <Button variant="ghost" onClick={onClose} className="flex-1 glass-secondary text-white hover:text-white">
              Отмена
            </Button>
            <Button onClick={handleSave} className="flex-1 bg-purple-600 hover:bg-purple-700 text-white">
              Применить ко всем
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
