import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Icon } from "@iconify/react";
import { useAppSelector, useAppDispatch } from "../../store/hooks";
import { userApi } from "../../api/userApi";
import { ThemeToggle } from "../common/ThemeToggle";
import { setUser, setAiSettings } from "../../store/slices/profileSlice";
import { setAccentColor as setAccentColorAction } from "../../store/slices/uiSlice";
import { setAccentColor } from "../../utils/colorUtils";
import { syncService } from "../../services/syncService";
import { setSyncStatus } from "../../store/slices/uiSlice";

interface HeaderProps {
  onFilterChange?: (hasFilters: boolean) => void;
  onToggleSidebar?: () => void;
}

export const Header: React.FC<HeaderProps> = ({
  onFilterChange,
  onToggleSidebar,
}) => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const user = useAppSelector((state) => state.profile.user);
  const selectedDate = useAppSelector((state) => state.notes.selectedDate);
  const selectedTag = useAppSelector((state) => state.notes.selectedTag);
  const searchQuery = useAppSelector((state) => state.notes.searchQuery);
  const offlineMode = useAppSelector((state) => state.notes.offlineMode);
  const pendingSyncCount = useAppSelector((state) => state.notes.pendingSyncCount);
  const syncStatus = useAppSelector((state) => state.ui.syncStatus);

  useEffect(() => {
    loadUserInfo();
  }, []);

  useEffect(() => {
    const hasFilters = !!(selectedDate || selectedTag || searchQuery);
    onFilterChange?.(hasFilters);
  }, [selectedDate, selectedTag, searchQuery, onFilterChange]);

  const loadUserInfo = async () => {
    try {
      const userData = await userApi.getProfile();
      dispatch(setUser(userData));

      // Устанавливаем цвет акцента из профиля пользователя
      const accent = userData.accent_color || "#007bff";
      dispatch(setAccentColorAction(accent));
      setAccentColor(accent);

      // Применяем настройку цветных иконок
      const coloredIcons = userData.colored_icons !== undefined ? userData.colored_icons === 1 : true;
      if (coloredIcons) {
        document.body.classList.add("colored-icons");
      } else {
        document.body.classList.remove("colored-icons");
      }

      // Загружаем AI настройки
      try {
        const aiSettings = await userApi.getAiSettings();
        dispatch(setAiSettings(aiSettings));
      } catch (aiError) {
        console.error("Ошибка загрузки AI настроек:", aiError);
      }
    } catch (error) {
      console.error("Ошибка загрузки информации о пользователе:", error);
    }
  };

  const handleManualSync = async () => {
    dispatch(setSyncStatus('syncing'));
    await syncService.startSync();
  };

  return (
    <>
      {/* Кнопка мобильного меню */}
      {onToggleSidebar && (
        <button className="mobile-menu-btn" onClick={onToggleSidebar}>
          <Icon icon="mdi:menu" />
        </button>
      )}

      <header className="notes-header">
        <div className="notes-header-left">
          <span>
            <Icon icon="mdi:note-text" /> Мои заметки
          </span>
        </div>
        <div className="user-info">
          {/* Offline/Sync индикатор */}
          {offlineMode ? (
            <div className="offline-indicator" title="Работаем в offline режиме">
              <Icon icon="mdi:wifi-off" style={{ color: '#ff9800' }} />
            </div>
          ) : pendingSyncCount > 0 ? (
            <button
              className="sync-indicator"
              title={`Синхронизировать ${pendingSyncCount} заметок`}
              onClick={handleManualSync}
              disabled={syncStatus === 'syncing'}
            >
              {syncStatus === 'syncing' ? (
                <Icon icon="mdi:loading" className="spinning" />
              ) : (
                <>
                  <Icon icon="mdi:cloud-upload" style={{ color: '#007bff' }} />
                  <span className="sync-badge">{pendingSyncCount}</span>
                </>
              )}
            </button>
          ) : syncStatus === 'syncing' ? (
            <div className="sync-indicator">
              <Icon icon="mdi:loading" className="spinning" style={{ color: '#007bff' }} />
            </div>
          ) : null}

          {user?.avatar ? (
            <div
              className="user-avatar-mini"
              style={{ display: "block" }}
              title="Перейти в профиль"
              onClick={() => navigate("/profile")}
            >
              <img src={user.avatar} alt="Аватар" loading="lazy" />
            </div>
          ) : (
            <div
              className="user-avatar-mini user-avatar-placeholder-mini"
              style={{ display: "flex" }}
              title="Перейти в профиль"
              onClick={() => navigate("/profile")}
            >
              <Icon icon="mdi:account" />
            </div>
          )}
          <ThemeToggle />
          <button
            className="settings-icon-btn"
            title="Настройки"
            onClick={() => navigate("/settings")}
          >
            <Icon icon="mdi:cog" />
          </button>
        </div>
      </header>
    </>
  );
};
