import { useState, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { X, Trash2, ChevronDown, ChevronUp, Clock, Calendar, Snowflake, Plus } from "lucide-react"
import { useMutation, useQueryClient, useQuery } from "@tanstack/react-query"
import { habitsApi } from "../api/habits"
import { format, parseISO, isBefore, isAfter, startOfDay } from "date-fns"
import { ru } from "date-fns/locale"
import clsx from "clsx"

const COLORS = [
  "#6366f1", "#8b5cf6", "#d946ef", "#ec4899", "#f43f5e",
  "#f97316", "#eab308", "#22c55e", "#14b8a6", "#0ea5e9",
]

const ICON_CATEGORIES = [
  { name: "Спорт", icons: ["💪", "🏃", "🚴", "🏊", "🧘", "⚽", "🏀", "🎾"] },
  { name: "Здоровье", icons: ["💊", "💉", "🩺", "🧠", "😴", "💤", "🦷", "👁️"] },
  { name: "Продуктивность", icons: ["📚", "📖", "✏️", "💻", "🎯", "📝", "📅", "⏰"] },
  { name: "Дом", icons: ["🏠", "🧹", "🧺", "🍳", "🛒", "🔧", "🪴"] },
  { name: "Финансы", icons: ["💰", "💳", "📊", "💵", "🏦"] },
  { name: "Социальное", icons: ["👥", "💬", "📞", "👪", "❤️"] },
  { name: "Хобби", icons: ["🎨", "🎵", "🎸", "🎮", "📷", "✈️", "🚗"] },
  { name: "Еда/вода", icons: ["🥗", "🍎", "🥤", "☕", "🍽️", "💧"] },
  { name: "Разное", icons: ["⭐", "🎉", "✨", "🔥", "🌟", "💎", "🎁"] },
]

const DAYS = [
  { id: 1, short: "Пн" },
  { id: 2, short: "Вт" },
  { id: 3, short: "Ср" },
  { id: 4, short: "Чт" },
  { id: 5, short: "Пт" },
  { id: 6, short: "Сб" },
  { id: 7, short: "Вс" },
]

export default function EditHabitModal({ open, onClose, habit }) {
  const [name, setName] = useState("")
  const [description, setDescription] = useState("")
  const [color, setColor] = useState(COLORS[0])
  const [icon, setIcon] = useState("✨")
  const [frequency, setFrequency] = useState("daily")
  const [targetDays, setTargetDays] = useState([1, 2, 3, 4, 5, 6, 7])
  const [intervalDays, setIntervalDays] = useState(3)
  const [reminderTime, setReminderTime] = useState("")
  const [startDate, setStartDate] = useState("")
  const [error, setError] = useState("")
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [showAllIcons, setShowAllIcons] = useState(false)
  const [showFreezes, setShowFreezes] = useState(false)
  const [showAddFreeze, setShowAddFreeze] = useState(false)
  const [freezeStart, setFreezeStart] = useState("")
  const [freezeEnd, setFreezeEnd] = useState("")
  const [freezeReason, setFreezeReason] = useState("")
  
  const queryClient = useQueryClient()

  // Load freezes for this habit
  const { data: freezes = [], refetch: refetchFreezes } = useQuery({
    queryKey: ['habit-freezes', habit?.id],
    queryFn: () => habitsApi.getFreezes(habit.id),
    enabled: !!habit?.id && open,
  })

  useEffect(() => {
    if (habit && open) {
      setName(habit.name || "")
      setDescription(habit.description || "")
      setColor(habit.color || COLORS[0])
      setIcon(habit.icon || "✨")
      setFrequency(habit.frequency || "daily")
      setTargetDays(habit.target_days || [1, 2, 3, 4, 5, 6, 7])
      setIntervalDays(habit.target_count || 3)
      setReminderTime(habit.reminder_time || "")
      if (habit.start_date) {
        setStartDate(habit.start_date)
      } else if (habit.created_at) {
        setStartDate(format(parseISO(habit.created_at), "yyyy-MM-dd"))
      } else {
        setStartDate(format(new Date(), "yyyy-MM-dd"))
      }
      setError("")
      setShowDeleteConfirm(false)
      setShowAllIcons(false)
      setShowFreezes(false)
      setShowAddFreeze(false)
      setFreezeStart("")
      setFreezeEnd("")
      setFreezeReason("")
    }
  }, [habit, open])

  const updateMutation = useMutation({
    mutationFn: (data) => habitsApi.update(habit.id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["habits"] })
      queryClient.invalidateQueries({ queryKey: ["stats"] })
      onClose()
    },
    onError: (err) => {
      setError(err.response?.data?.error || "Ошибка сохранения")
    },
  })

  const deleteMutation = useMutation({
    mutationFn: () => habitsApi.delete(habit.id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["habits"] })
      queryClient.invalidateQueries({ queryKey: ["stats"] })
      onClose()
    },
    onError: (err) => {
      setError(err.response?.data?.error || "Ошибка удаления")
    },
  })

  const addFreezeMutation = useMutation({
    mutationFn: (data) => habitsApi.addFreeze(habit.id, data),
    onSuccess: () => {
      refetchFreezes()
      queryClient.invalidateQueries({ queryKey: ["habits"] })
      setShowAddFreeze(false)
      setFreezeStart("")
      setFreezeEnd("")
      setFreezeReason("")
    },
    onError: (err) => {
      setError(err.response?.data?.error || "Ошибка создания заморозки")
    },
  })

  const deleteFreezeMutation = useMutation({
    mutationFn: (freezeId) => habitsApi.deleteFreeze(habit.id, freezeId),
    onSuccess: () => {
      refetchFreezes()
      queryClient.invalidateQueries({ queryKey: ["habits"] })
    },
  })

  const handleClose = () => {
    setError("")
    setShowDeleteConfirm(false)
    setShowAllIcons(false)
    setShowFreezes(false)
    setShowAddFreeze(false)
    onClose()
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    if (!name.trim()) {
      setError("Введи название привычки")
      return
    }
    if (frequency === "weekly" && targetDays.length === 0) {
      setError("Выбери хотя бы один день недели")
      return
    }
    const interval = parseInt(intervalDays) || 0
    if (frequency === "interval" && (interval < 2 || interval > 30)) {
      setError("Интервал должен быть от 2 до 30 дней")
      return
    }
    
    const data = { name, description, color, icon, frequency, start_date: startDate }
    if (frequency === "weekly") {
      data.target_days = targetDays
    }
    if (frequency === "interval") {
      data.target_count = parseInt(intervalDays)
    }
    data.reminder_time = reminderTime || null
    
    updateMutation.mutate(data)
  }

  const handleDelete = () => {
    deleteMutation.mutate()
  }

  const handleAddFreeze = () => {
    if (!freezeStart || !freezeEnd) {
      setError("Укажи даты начала и окончания заморозки")
      return
    }
    if (isBefore(parseISO(freezeEnd), parseISO(freezeStart))) {
      setError("Дата окончания должна быть после даты начала")
      return
    }
    setError("")
    addFreezeMutation.mutate({
      start_date: freezeStart,
      end_date: freezeEnd,
      reason: freezeReason,
    })
  }

  const toggleDay = (dayId) => {
    setTargetDays(prev => 
      prev.includes(dayId)
        ? prev.filter(d => d !== dayId)
        : [...prev, dayId].sort((a, b) => a - b)
    )
  }

  const today = startOfDay(new Date())
  const activeFreezes = freezes.filter(f => !isBefore(parseISO(f.end_date), today))
  const pastFreezes = freezes.filter(f => isBefore(parseISO(f.end_date), today))

  const popularIcons = ["✨", "💪", "📚", "🏃", "💧", "🧘", "💤", "🎯", "✏️", "🍎"]

  if (!habit) return null

  return (
    <AnimatePresence>
      {open && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={handleClose}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-40"
          />
          <motion.div
            initial={{ opacity: 0, y: 100 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 100 }}
            className="fixed bottom-0 left-0 right-0 z-50 p-4 sm:p-0 sm:flex sm:items-center sm:justify-center sm:inset-0"
          >
            <div className="bg-white dark:bg-gray-900 rounded-2xl sm:rounded-2xl w-full max-w-md max-h-[85vh] overflow-auto">
              <div className="sticky top-0 bg-white dark:bg-gray-900 border-b border-gray-100 dark:border-gray-800 px-4 py-3 flex items-center justify-between z-10">
                <h2 className="text-lg font-semibold">Редактировать привычку</h2>
                <button
                  onClick={handleClose}
                  className="p-2 text-gray-400 dark:text-gray-500 hover:text-gray-600 rounded-xl hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800"
                >
                  <X size={20} />
                </button>
              </div>

              {showDeleteConfirm ? (
                <div className="p-6 text-center">
                  <div className="w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4">
                    <Trash2 className="w-8 h-8 text-red-500" />
                  </div>
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">Удалить привычку?</h3>
                  <p className="text-gray-500 dark:text-gray-400 dark:text-gray-500 mb-6">
                    Привычка "{habit.name}" и вся её история будут удалены безвозвратно.
                  </p>
                  <div className="flex gap-3">
                    <button
                      onClick={() => setShowDeleteConfirm(false)}
                      className="flex-1 btn bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200"
                    >
                      Отмена
                    </button>
                    <button
                      onClick={handleDelete}
                      disabled={deleteMutation.isPending}
                      className="flex-1 btn bg-red-500 text-white hover:bg-red-600"
                    >
                      {deleteMutation.isPending ? "Удаляем..." : "Удалить"}
                    </button>
                  </div>
                </div>
              ) : (
                <form onSubmit={handleSubmit} className="p-4 space-y-4">
                  {error && (
                    <div className="p-3 rounded-xl bg-red-50 text-red-600 text-sm">
                      {error}
                    </div>
                  )}

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
                      Название
                    </label>
                    <input
                      type="text"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className="input"
                      placeholder="Например: Пить воду"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
                      Описание (опционально)
                    </label>
                    <input
                      type="text"
                      value={description}
                      onChange={(e) => setDescription(e.target.value)}
                      className="input"
                      placeholder="8 стаканов в день"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Периодичность
                    </label>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => setFrequency("daily")}
                        className={clsx(
                          "flex-1 py-2.5 px-3 rounded-xl font-medium text-sm transition-all",
                          frequency === "daily"
                            ? "bg-primary-500 text-white shadow-lg shadow-primary-500/30"
                            : "bg-gray-100 dark:bg-gray-800 text-gray-600 hover:bg-gray-200"
                        )}
                      >
                        Ежедневно
                      </button>
                      <button
                        type="button"
                        onClick={() => setFrequency("weekly")}
                        className={clsx(
                          "flex-1 py-2.5 px-3 rounded-xl font-medium text-sm transition-all",
                          frequency === "weekly"
                            ? "bg-primary-500 text-white shadow-lg shadow-primary-500/30"
                            : "bg-gray-100 dark:bg-gray-800 text-gray-600 hover:bg-gray-200"
                        )}
                      >
                        По дням
                      </button>
                      <button
                        type="button"
                        onClick={() => setFrequency("interval")}
                        className={clsx(
                          "flex-1 py-2.5 px-3 rounded-xl font-medium text-sm transition-all",
                          frequency === "interval"
                            ? "bg-primary-500 text-white shadow-lg shadow-primary-500/30"
                            : "bg-gray-100 dark:bg-gray-800 text-gray-600 hover:bg-gray-200"
                        )}
                      >
                        Интервал
                      </button>
                    </div>
                  </div>

                  {frequency === "weekly" && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: "auto" }}
                      exit={{ opacity: 0, height: 0 }}
                    >
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Дни недели
                      </label>
                      <div className="flex gap-1.5">
                        {DAYS.map((day) => (
                          <button
                            key={day.id}
                            type="button"
                            onClick={() => toggleDay(day.id)}
                            className={clsx(
                              "flex-1 py-2 rounded-lg font-medium text-sm transition-all",
                              targetDays.includes(day.id)
                                ? "bg-primary-500 text-white shadow-md"
                                : "bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400 dark:text-gray-500 hover:bg-gray-200"
                            )}
                          >
                            {day.short}
                          </button>
                        ))}
                      </div>
                    </motion.div>
                  )}

                  {frequency === "interval" && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: "auto" }}
                      exit={{ opacity: 0, height: 0 }}
                    >
                      <div className="flex items-center gap-3">
                        <span className="text-gray-500 dark:text-gray-400 dark:text-gray-500">Каждые</span>
                        <input
                          type="number"
                          min="2"
                          max="30"
                          value={intervalDays}
                          onChange={(e) => setIntervalDays(e.target.value === "" ? "" : parseInt(e.target.value) || "")}
                          className="input w-20 text-center"
                        />
                        <span className="text-gray-500 dark:text-gray-400 dark:text-gray-500">дней</span>
                      </div>
                    </motion.div>
                  )}

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Дата начала
                    </label>
                    <div className="relative">
                      <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500" size={18} />
                      <input
                        type="date"
                        value={startDate}
                        onChange={(e) => setStartDate(e.target.value)}
                        className="input pl-10"
                      />
                    </div>
                    <p className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500 mt-1">
                      {frequency === "interval"
                        ? "Интервал считается от этой даты"
                        : "Привычка появится начиная с этой даты"}
                    </p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Напоминание (опционально)
                    </label>
                    <div className="relative">
                      <Clock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500" size={18} />
                      <input
                        type="time"
                        value={reminderTime}
                        onChange={(e) => setReminderTime(e.target.value)}
                        className="input pl-10"
                      />
                    </div>
                    <p className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500 mt-1">
                      Получишь напоминание в Telegram в указанное время
                    </p>
                  </div>

                  {/* Freezes section */}
                  <div className="border-t pt-4">
                    <button
                      type="button"
                      onClick={() => setShowFreezes(!showFreezes)}
                      className="flex items-center justify-between w-full text-left"
                    >
                      <div className="flex items-center gap-2">
                        <Snowflake className="w-5 h-5 text-cyan-500" />
                        <span className="font-medium text-gray-700 dark:text-gray-300">Заморозки</span>
                        {activeFreezes.length > 0 && (
                          <span className="px-2 py-0.5 bg-cyan-100 text-cyan-700 rounded-full text-xs">
                            {activeFreezes.length}
                          </span>
                        )}
                      </div>
                      {showFreezes ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
                    </button>
                    <p className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500 mt-1">
                      Поставь привычку на паузу на время отпуска или болезни
                    </p>

                    <AnimatePresence>
                      {showFreezes && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: "auto" }}
                          exit={{ opacity: 0, height: 0 }}
                          className="mt-3 space-y-3"
                        >
                          {/* Active freezes */}
                          {activeFreezes.length > 0 && (
                            <div className="space-y-2">
                              {activeFreezes.map((freeze) => {
                                const isActive = !isBefore(parseISO(freeze.end_date), today) && 
                                                 !isAfter(parseISO(freeze.start_date), today)
                                return (
                                  <div
                                    key={freeze.id}
                                    className={clsx(
                                      "flex items-center justify-between p-3 rounded-xl",
                                      isActive ? "bg-cyan-50 border border-cyan-200" : "bg-gray-50 dark:bg-gray-800"
                                    )}
                                  >
                                    <div className="flex items-center gap-2">
                                      <Snowflake className={clsx(
                                        "w-4 h-4",
                                        isActive ? "text-cyan-500" : "text-gray-400 dark:text-gray-500"
                                      )} />
                                      <div>
                                        <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                          {format(parseISO(freeze.start_date), "d MMM", { locale: ru })} — {format(parseISO(freeze.end_date), "d MMM yyyy", { locale: ru })}
                                        </p>
                                        {freeze.reason && (
                                          <p className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500">{freeze.reason}</p>
                                        )}
                                      </div>
                                      {isActive && (
                                        <span className="px-2 py-0.5 bg-cyan-200 text-cyan-800 rounded-full text-xs">
                                          активна
                                        </span>
                                      )}
                                    </div>
                                    <button
                                      type="button"
                                      onClick={() => deleteFreezeMutation.mutate(freeze.id)}
                                      className="p-1.5 text-gray-400 dark:text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-lg"
                                    >
                                      <Trash2 size={16} />
                                    </button>
                                  </div>
                                )
                              })}
                            </div>
                          )}

                          {/* Add freeze form */}
                          {showAddFreeze ? (
                            <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-xl space-y-3">
                              <div className="grid grid-cols-2 gap-2">
                                <div>
                                  <label className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500">Начало</label>
                                  <input
                                    type="date"
                                    value={freezeStart}
                                    onChange={(e) => setFreezeStart(e.target.value)}
                                    min={format(new Date(), "yyyy-MM-dd")}
                                    className="input text-sm"
                                  />
                                </div>
                                <div>
                                  <label className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500">Окончание</label>
                                  <input
                                    type="date"
                                    value={freezeEnd}
                                    onChange={(e) => setFreezeEnd(e.target.value)}
                                    min={freezeStart || format(new Date(), "yyyy-MM-dd")}
                                    className="input text-sm"
                                  />
                                </div>
                              </div>
                              <input
                                type="text"
                                value={freezeReason}
                                onChange={(e) => setFreezeReason(e.target.value)}
                                placeholder="Причина (опционально)"
                                className="input text-sm"
                              />
                              <div className="flex gap-2">
                                <button
                                  type="button"
                                  onClick={() => setShowAddFreeze(false)}
                                  className="flex-1 btn bg-gray-100 dark:bg-gray-800 text-gray-600 text-sm"
                                >
                                  Отмена
                                </button>
                                <button
                                  type="button"
                                  onClick={handleAddFreeze}
                                  disabled={addFreezeMutation.isPending}
                                  className="flex-1 btn bg-cyan-500 text-white text-sm hover:bg-cyan-600"
                                >
                                  {addFreezeMutation.isPending ? "..." : "Добавить"}
                                </button>
                              </div>
                            </div>
                          ) : (
                            <button
                              type="button"
                              onClick={() => setShowAddFreeze(true)}
                              className="flex items-center gap-2 w-full p-3 bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800 rounded-xl text-sm text-gray-600 transition-colors"
                            >
                              <Plus size={16} />
                              Добавить заморозку
                            </button>
                          )}

                          {/* Past freezes */}
                          {pastFreezes.length > 0 && (
                            <details className="text-sm">
                              <summary className="text-gray-500 dark:text-gray-400 dark:text-gray-500 cursor-pointer hover:text-gray-700 dark:text-gray-300">
                                Прошлые заморозки ({pastFreezes.length})
                              </summary>
                              <div className="mt-2 space-y-1">
                                {pastFreezes.map((freeze) => (
                                  <div key={freeze.id} className="flex items-center justify-between p-2 rounded-lg bg-gray-50 dark:bg-gray-800 text-gray-500 dark:text-gray-400 dark:text-gray-500">
                                    <span>
                                      {format(parseISO(freeze.start_date), "d MMM", { locale: ru })} — {format(parseISO(freeze.end_date), "d MMM yyyy", { locale: ru })}
                                      {freeze.reason && " — " + freeze.reason}
                                    </span>
                                    <button
                                      type="button"
                                      onClick={() => deleteFreezeMutation.mutate(freeze.id)}
                                      className="p-1 text-gray-400 dark:text-gray-500 hover:text-red-500"
                                    >
                                      <Trash2 size={14} />
                                    </button>
                                  </div>
                                ))}
                              </div>
                            </details>
                          )}
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Иконка
                    </label>
                    <div className="flex flex-wrap gap-2">
                      {popularIcons.map((ic) => (
                        <button
                          key={ic}
                          type="button"
                          onClick={() => setIcon(ic)}
                          className={clsx(
                            "w-10 h-10 rounded-xl flex items-center justify-center text-xl transition-all",
                            icon === ic
                              ? "bg-primary-100 ring-2 ring-primary-500"
                              : "bg-gray-100 dark:bg-gray-800 hover:bg-gray-200"
                          )}
                        >
                          {ic}
                        </button>
                      ))}
                    </div>
                    
                    <button
                      type="button"
                      onClick={() => setShowAllIcons(!showAllIcons)}
                      className="mt-2 flex items-center gap-1 text-sm text-primary-600 hover:text-primary-700"
                    >
                      {showAllIcons ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
                      {showAllIcons ? "Скрыть" : "Все иконки"}
                    </button>

                    <AnimatePresence>
                      {showAllIcons && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: "auto" }}
                          exit={{ opacity: 0, height: 0 }}
                          className="mt-3 space-y-3"
                        >
                          {ICON_CATEGORIES.map((category) => (
                            <div key={category.name}>
                              <p className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500 mb-1.5">{category.name}</p>
                              <div className="flex flex-wrap gap-1.5">
                                {category.icons.map((ic) => (
                                  <button
                                    key={ic}
                                    type="button"
                                    onClick={() => setIcon(ic)}
                                    className={clsx(
                                      "w-9 h-9 rounded-lg flex items-center justify-center text-lg transition-all",
                                      icon === ic
                                        ? "bg-primary-100 ring-2 ring-primary-500"
                                        : "bg-gray-100 dark:bg-gray-800 hover:bg-gray-200"
                                    )}
                                  >
                                    {ic}
                                  </button>
                                ))}
                              </div>
                            </div>
                          ))}
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Цвет
                    </label>
                    <div className="flex flex-wrap gap-2">
                      {COLORS.map((c) => (
                        <button
                          key={c}
                          type="button"
                          onClick={() => setColor(c)}
                          className={clsx(
                            "w-8 h-8 rounded-full transition-all",
                            color === c ? "ring-2 ring-offset-2 ring-gray-400 scale-110" : ""
                          )}
                          style={{ backgroundColor: c }}
                        />
                      ))}
                    </div>
                  </div>

                  <div className="pt-2 space-y-3">
                    <button
                      type="submit"
                      disabled={updateMutation.isPending}
                      className="btn btn-primary w-full"
                    >
                      {updateMutation.isPending ? "Сохраняем..." : "Сохранить изменения"}
                    </button>
                    
                    <button
                      type="button"
                      onClick={() => setShowDeleteConfirm(true)}
                      className="btn w-full bg-red-50 text-red-600 hover:bg-red-100 flex items-center justify-center gap-2"
                    >
                      <Trash2 size={18} />
                      Удалить привычку
                    </button>
                  </div>
                </form>
              )}
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  )
}
