import { useState, useEffect } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { ArrowLeft, Bell, MessageCircle, Globe, Save, Copy, Check, User, Sun, Moon, Palette } from "lucide-react"
import { Link } from "react-router-dom"
import { profileApi } from "../api/profile"
import { useTheme } from "../contexts/ThemeContext"
import Navigation from "../components/Navigation"

const TIMEZONES = [
  { value: "Europe/Moscow", label: "Москва (UTC+3)" },
  { value: "Europe/Kaliningrad", label: "Калининград (UTC+2)" },
  { value: "Europe/Samara", label: "Самара (UTC+4)" },
  { value: "Asia/Yekaterinburg", label: "Екатеринбург (UTC+5)" },
  { value: "Asia/Omsk", label: "Омск (UTC+6)" },
  { value: "Asia/Krasnoyarsk", label: "Красноярск (UTC+7)" },
  { value: "Asia/Irkutsk", label: "Иркутск (UTC+8)" },
  { value: "Asia/Yakutsk", label: "Якутск (UTC+9)" },
  { value: "Asia/Vladivostok", label: "Владивосток (UTC+10)" },
  { value: "Asia/Magadan", label: "Магадан (UTC+11)" },
  { value: "Asia/Kamchatka", label: "Камчатка (UTC+12)" },
  { value: "Asia/Tokyo", label: "Токио (UTC+9)" },
  { value: "Europe/London", label: "Лондон (UTC+0)" },
  { value: "Europe/Berlin", label: "Берлин (UTC+1)" },
  { value: "America/New_York", label: "Нью-Йорк (UTC-5)" },
  { value: "America/Los_Angeles", label: "Лос-Анджелес (UTC-8)" },
]

export default function Settings() {
  const queryClient = useQueryClient()
  const { theme, toggleTheme } = useTheme()
  const [copied, setCopied] = useState(false)
  const [username, setUsername] = useState("")
  const [chatId, setChatId] = useState("")
  const [notificationsEnabled, setNotificationsEnabled] = useState(true)
  const [timezone, setTimezone] = useState("Europe/Moscow")
  const [morningTime, setMorningTime] = useState("09:00")
  const [eveningTime, setEveningTime] = useState("21:00")
  const [hasChanges, setHasChanges] = useState(false)

  const { data: profile, isLoading } = useQuery({
    queryKey: ["profile"],
    queryFn: profileApi.get,
  })

  useEffect(() => {
    if (profile) {
      setUsername(profile.username || "")
      setChatId(profile.telegram_chat_id?.toString() || "")
      setNotificationsEnabled(profile.notifications_enabled ?? true)
      setTimezone(profile.timezone || "Europe/Moscow")
      setMorningTime(profile.morning_reminder_time || "09:00")
      setEveningTime(profile.evening_reminder_time || "21:00")
    }
  }, [profile])

  useEffect(() => {
    if (profile) {
      const changed =
        username !== (profile.username || "") ||
        (chatId !== (profile.telegram_chat_id?.toString() || "")) ||
        notificationsEnabled !== (profile.notifications_enabled ?? true) ||
        timezone !== (profile.timezone || "Europe/Moscow") ||
        morningTime !== (profile.morning_reminder_time || "09:00") ||
        eveningTime !== (profile.evening_reminder_time || "21:00")
      setHasChanges(changed)
    }
  }, [username, chatId, notificationsEnabled, timezone, morningTime, eveningTime, profile])

  const mutation = useMutation({
    mutationFn: profileApi.update,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["profile"] })
      setHasChanges(false)
    },
  })

  const handleSave = () => {
    const data = {
      notifications_enabled: notificationsEnabled,
      timezone: timezone,
      morning_reminder_time: morningTime,
      evening_reminder_time: eveningTime,
    }
    
    if (username && username !== profile?.username) {
      data.username = username
    }
    
    if (chatId) {
      data.telegram_chat_id = parseInt(chatId, 10)
    }
    
    mutation.mutate(data)
  }

  const copyInstruction = () => {
    navigator.clipboard.writeText("@pulse_tracking_bot")
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-surface-50 dark:bg-gray-950 flex items-center justify-center">
        <div className="w-10 h-10 border-4 border-primary-500 border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-surface-50 dark:bg-gray-950 pb-24 transition-colors duration-300">
      {/* Header */}
      <header className="bg-white/80 dark:bg-gray-900/80 backdrop-blur-xl sticky top-0 z-40 border-b border-gray-100 dark:border-gray-800">
        <div className="max-w-lg mx-auto px-4 py-4 flex items-center gap-3">
          <Link to="/" className="p-2 -ml-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white rounded-xl hover:bg-gray-100 dark:hover:bg-gray-800">
            <ArrowLeft size={20} />
          </Link>
          <h1 className="text-xl font-bold dark:text-white">Настройки</h1>
        </div>
      </header>

      <main className="max-w-lg mx-auto px-4 py-6 space-y-6">
        
        {/* Theme Section */}
        <section className="bg-white dark:bg-gray-900 rounded-2xl p-4 shadow-sm dark:shadow-none border border-transparent dark:border-gray-800">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-violet-100 dark:bg-violet-900/30 flex items-center justify-center">
              <Palette className="text-violet-600 dark:text-violet-400" size={20} />
            </div>
            <div>
              <h2 className="font-semibold dark:text-white">Оформление</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">Выбери тему приложения</p>
            </div>
          </div>

          <button
            onClick={toggleTheme}
            className="w-full flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-800 rounded-xl transition-all hover:bg-gray-100 dark:hover:bg-gray-700"
          >
            <div className="flex items-center gap-3">
              {theme === "dark" ? (
                <Moon className="text-primary-500" size={22} />
              ) : (
                <Sun className="text-amber-500" size={22} />
              )}
              <span className="font-medium text-gray-900 dark:text-white">
                {theme === "dark" ? "Тёмная тема" : "Светлая тема"}
              </span>
            </div>
            <div className="relative">
              <div className={`w-14 h-8 rounded-full transition-colors duration-300 ${theme === "dark" ? "bg-primary-500" : "bg-gray-300"}`}>
                <div className={`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 flex items-center justify-center ${theme === "dark" ? "translate-x-7" : "translate-x-1"}`}>
                  {theme === "dark" ? (
                    <Moon className="text-primary-600" size={14} />
                  ) : (
                    <Sun className="text-amber-500" size={14} />
                  )}
                </div>
              </div>
            </div>
          </button>
        </section>

        {/* Profile Section */}
        <section className="bg-white dark:bg-gray-900 rounded-2xl p-4 shadow-sm dark:shadow-none border border-transparent dark:border-gray-800">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
              <User className="text-green-600 dark:text-green-400" size={20} />
            </div>
            <div>
              <h2 className="font-semibold dark:text-white">Профиль</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">Основная информация</p>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
              Имя пользователя
            </label>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="Ваше имя"
              className="input"
            />
          </div>
        </section>

        {/* Telegram Section */}
        <section className="bg-white dark:bg-gray-900 rounded-2xl p-4 shadow-sm dark:shadow-none border border-transparent dark:border-gray-800">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
              <MessageCircle className="text-blue-600 dark:text-blue-400" size={20} />
            </div>
            <div>
              <h2 className="font-semibold dark:text-white">Telegram</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">Получай уведомления в Telegram</p>
            </div>
          </div>

          <div className="space-y-4">
            <div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-xl">
              <p className="text-sm text-blue-800 dark:text-blue-300 mb-2">
                1. Напиши <code className="bg-blue-100 dark:bg-blue-800 px-1 rounded">/start</code> боту в Telegram
              </p>
              <button
                onClick={copyInstruction}
                className="flex items-center gap-2 text-sm font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
              >
                {copied ? <Check size={16} /> : <Copy size={16} />}
                {copied ? "Скопировано!" : "@pulse_tracking_bot"}
              </button>
              <p className="text-sm text-blue-800 dark:text-blue-300 mt-2">
                2. Скопируй Chat ID из ответа бота и вставь ниже
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
                Chat ID
              </label>
              <input
                type="text"
                value={chatId}
                onChange={(e) => setChatId(e.target.value.replace(/\D/g, ""))}
                placeholder="Например: 123456789"
                className="input"
              />
            </div>
          </div>
        </section>

        {/* Notifications Section */}
        <section className="bg-white dark:bg-gray-900 rounded-2xl p-4 shadow-sm dark:shadow-none border border-transparent dark:border-gray-800">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center">
              <Bell className="text-orange-600 dark:text-orange-400" size={20} />
            </div>
            <div>
              <h2 className="font-semibold dark:text-white">Уведомления</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">Настрой ежедневные уведомления</p>
            </div>
          </div>

          <div className="space-y-4">
            <label className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-xl cursor-pointer">
              <span className="text-sm font-medium dark:text-white">Включить уведомления</span>
              <div className="relative">
                <input
                  type="checkbox"
                  checked={notificationsEnabled}
                  onChange={(e) => setNotificationsEnabled(e.target.checked)}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-300 dark:bg-gray-600 rounded-full peer peer-checked:bg-primary-500 transition-colors"></div>
                <div className="absolute left-1 top-1 w-4 h-4 bg-white rounded-full peer-checked:translate-x-5 transition-transform"></div>
              </div>
            </label>

            {notificationsEnabled && (
              <>
                <div className="flex items-center gap-3 p-3 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl">
                  <Sun className="text-yellow-600 dark:text-yellow-400" size={20} />
                  <div className="flex-1">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                      Утреннее уведомление
                    </label>
                    <p className="text-xs text-gray-500 dark:text-gray-400">Задачи и привычки на сегодня</p>
                  </div>
                  <input
                    type="time"
                    value={morningTime}
                    onChange={(e) => setMorningTime(e.target.value)}
                    className="px-3 py-1.5 border border-gray-200 dark:border-gray-700 dark:bg-gray-800 dark:text-white rounded-lg text-sm"
                  />
                </div>

                <div className="flex items-center gap-3 p-3 bg-indigo-50 dark:bg-indigo-900/20 rounded-xl">
                  <Moon className="text-indigo-600 dark:text-indigo-400" size={20} />
                  <div className="flex-1">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                      Вечернее уведомление
                    </label>
                    <p className="text-xs text-gray-500 dark:text-gray-400">Итоги дня: выполнено / осталось</p>
                  </div>
                  <input
                    type="time"
                    value={eveningTime}
                    onChange={(e) => setEveningTime(e.target.value)}
                    className="px-3 py-1.5 border border-gray-200 dark:border-gray-700 dark:bg-gray-800 dark:text-white rounded-lg text-sm"
                  />
                </div>
              </>
            )}
          </div>
        </section>

        {/* Timezone Section */}
        <section className="bg-white dark:bg-gray-900 rounded-2xl p-4 shadow-sm dark:shadow-none border border-transparent dark:border-gray-800">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center">
              <Globe className="text-purple-600 dark:text-purple-400" size={20} />
            </div>
            <div>
              <h2 className="font-semibold dark:text-white">Часовой пояс</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">Для корректных напоминаний</p>
            </div>
          </div>

          <select
            value={timezone}
            onChange={(e) => setTimezone(e.target.value)}
            className="input"
          >
            {TIMEZONES.map((tz) => (
              <option key={tz.value} value={tz.value}>
                {tz.label}
              </option>
            ))}
          </select>
        </section>

        {/* Save Button */}
        {hasChanges && (
          <button
            onClick={handleSave}
            disabled={mutation.isPending}
            className="btn btn-primary w-full flex items-center justify-center gap-2"
          >
            <Save size={18} />
            {mutation.isPending ? "Сохраняем..." : "Сохранить изменения"}
          </button>
        )}

        {mutation.isSuccess && !hasChanges && (
          <div className="p-3 rounded-xl bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 text-sm text-center">
            ✅ Настройки сохранены
          </div>
        )}
      </main>

      <Navigation />
    </div>
  )
}
