import { useState, useMemo } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X, ChevronLeft, ChevronRight, Check } from 'lucide-react'
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameDay, isFuture, startOfDay, subMonths, addMonths, isToday } from 'date-fns'
import { ru } from 'date-fns/locale'
import clsx from 'clsx'

export default function LogHabitModal({ open, onClose, habit, completedDates = [], onLogDate }) {
  const [currentMonth, setCurrentMonth] = useState(new Date())
  const [selectedDate, setSelectedDate] = useState(null)
  const [isLogging, setIsLogging] = useState(false)

  const days = useMemo(() => {
    const start = startOfMonth(currentMonth)
    const end = endOfMonth(currentMonth)
    return eachDayOfInterval({ start, end })
  }, [currentMonth])

  // Convert completedDates to a Set for faster lookup
  const completedSet = useMemo(() => {
    const set = new Set()
    completedDates.forEach(d => {
      const dateStr = typeof d === 'string' ? d.split('T')[0] : format(d, 'yyyy-MM-dd')
      set.add(dateStr)
    })
    return set
  }, [completedDates])

  const isDateCompleted = (date) => {
    return completedSet.has(format(date, 'yyyy-MM-dd'))
  }

  const handleDateClick = (date) => {
    if (isFuture(startOfDay(date))) return
    if (isDateCompleted(date)) return
    setSelectedDate(date)
  }

  const handleConfirm = async () => {
    if (!selectedDate) return
    setIsLogging(true)
    try {
      await onLogDate(habit.id, format(selectedDate, 'yyyy-MM-dd'))
      onClose()
    } catch (error) {
      console.error('Failed to log habit:', error)
    } finally {
      setIsLogging(false)
    }
  }

  // Get first day of week offset
  const firstDayOfMonth = startOfMonth(currentMonth)
  const startOffset = (firstDayOfMonth.getDay() + 6) % 7 // Monday = 0

  if (!open) return null

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
        onClick={onClose}
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 20 }}
          onClick={e => e.stopPropagation()}
          className="bg-white dark:bg-gray-900 rounded-3xl shadow-2xl w-full max-w-sm overflow-hidden"
        >
          {/* Header */}
          <div className="p-5 border-b border-gray-100 dark:border-gray-800 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div
                className="w-10 h-10 rounded-xl flex items-center justify-center text-xl"
                style={{ backgroundColor: habit?.color + '20' }}
              >
                {habit?.icon || '✨'}
              </div>
              <div>
                <h2 className="text-lg font-display font-bold text-gray-900 dark:text-white">Отметить привычку</h2>
                <p className="text-sm text-gray-500 dark:text-gray-400 dark:text-gray-500">{habit?.name}</p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="p-2 text-gray-400 dark:text-gray-500 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800 rounded-xl transition-colors"
            >
              <X size={20} />
            </button>
          </div>

          {/* Calendar */}
          <div className="p-5">
            {/* Month navigation */}
            <div className="flex items-center justify-between mb-4">
              <button
                onClick={() => setCurrentMonth(m => subMonths(m, 1))}
                className="p-2 text-gray-400 dark:text-gray-500 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800 rounded-xl transition-colors"
              >
                <ChevronLeft size={20} />
              </button>
              <span className="font-semibold text-gray-900 dark:text-white capitalize">
                {format(currentMonth, 'LLLL yyyy', { locale: ru })}
              </span>
              <button
                onClick={() => setCurrentMonth(m => addMonths(m, 1))}
                disabled={isSameDay(startOfMonth(currentMonth), startOfMonth(new Date()))}
                className={clsx(
                  "p-2 rounded-xl transition-colors",
                  isSameDay(startOfMonth(currentMonth), startOfMonth(new Date()))
                    ? "text-gray-200 cursor-not-allowed"
                    : "text-gray-400 dark:text-gray-500 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800"
                )}
              >
                <ChevronRight size={20} />
              </button>
            </div>

            {/* Weekday headers */}
            <div className="grid grid-cols-7 gap-1 mb-2">
              {['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'].map(day => (
                <div key={day} className="text-center text-xs font-medium text-gray-400 dark:text-gray-500 py-2">
                  {day}
                </div>
              ))}
            </div>

            {/* Calendar grid */}
            <div className="grid grid-cols-7 gap-1">
              {/* Empty cells for offset */}
              {Array.from({ length: startOffset }).map((_, i) => (
                <div key={`offset-${i}`} className="aspect-square" />
              ))}
              
              {/* Days */}
              {days.map(day => {
                const completed = isDateCompleted(day)
                const future = isFuture(startOfDay(day))
                const selected = selectedDate && isSameDay(day, selectedDate)
                const today = isToday(day)

                return (
                  <button
                    key={day.toISOString()}
                    onClick={() => handleDateClick(day)}
                    disabled={future || completed}
                    className={clsx(
                      "aspect-square rounded-xl flex items-center justify-center text-sm font-medium transition-all",
                      future && "text-gray-200 cursor-not-allowed",
                      completed && "bg-green-100 text-green-600 cursor-default",
                      selected && !completed && "bg-primary-500 text-white shadow-lg shadow-primary-500/30",
                      !future && !completed && !selected && "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800",
                      today && !selected && !completed && "ring-2 ring-primary-200"
                    )}
                  >
                    {completed ? (
                      <Check size={16} className="text-green-600" />
                    ) : (
                      format(day, 'd')
                    )}
                  </button>
                )
              })}
            </div>

            {/* Selected date info */}
            {selectedDate && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="mt-4 p-3 bg-primary-50 rounded-xl text-center"
              >
                <p className="text-sm text-primary-700">
                  Выбрано: <span className="font-semibold">{format(selectedDate, 'd MMMM yyyy', { locale: ru })}</span>
                </p>
              </motion.div>
            )}
          </div>

          {/* Actions */}
          <div className="p-5 pt-0 flex gap-3">
            <button
              onClick={onClose}
              className="flex-1 py-3 px-4 rounded-xl font-semibold text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 transition-colors"
            >
              Отмена
            </button>
            <button
              onClick={handleConfirm}
              disabled={!selectedDate || isLogging}
              className={clsx(
                "flex-1 py-3 px-4 rounded-xl font-semibold text-white transition-all",
                selectedDate && !isLogging
                  ? "bg-primary-500 hover:bg-primary-600 shadow-lg shadow-primary-500/30"
                  : "bg-gray-300 cursor-not-allowed"
              )}
            >
              {isLogging ? 'Сохранение...' : 'Отметить'}
            </button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  )
}
