import React, { useRef, useState } from "react";
import { Icon } from "@iconify/react";
import { Header } from "../components/layout/Header";
import { Sidebar } from "../components/layout/Sidebar";
import { MobileSidebar } from "../components/layout/MobileSidebar";
import { NoteEditor } from "../components/notes/NoteEditor";
import { NotesList, NotesListRef } from "../components/notes/NotesList";
import { ImageModal } from "../components/common/ImageModal";
import { MergeNotesModal } from "../components/notes/MergeNotesModal";
import { Modal } from "../components/common/Modal";
import { offlineNotesApi } from "../api/offlineNotesApi";
import { useAppSelector, useAppDispatch } from "../store/hooks";
import { useTheme } from "../hooks/useTheme";
import { useNotification } from "../hooks/useNotification";
import {
  setSelectedDate,
  setSelectedTag,
  setSearchQuery,
} from "../store/slices/notesSlice";

const NotesPage: React.FC = () => {
  const allNotes = useAppSelector((state) => state.notes.allNotes);
  const notes = useAppSelector((state) => state.notes.notes);
  const notesListRef = useRef<NotesListRef>(null);
  const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);
  const [selectedNoteIds, setSelectedNoteIds] = useState<(number | string)[]>([]);
  const [isMergeModalOpen, setIsMergeModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const dispatch = useAppDispatch();
  const { theme } = useTheme();
  const { showNotification } = useNotification();
  const selectedDate = useAppSelector((state) => state.notes.selectedDate);
  const selectedTag = useAppSelector((state) => state.notes.selectedTag);
  const searchQuery = useAppSelector((state) => state.notes.searchQuery);
  const aiEnabled = useAppSelector((state) => state.profile.aiEnabled);

  const hasFilters = !!(selectedDate || selectedTag || searchQuery);

  const handleClearFilters = () => {
    dispatch(setSelectedDate(null));
    dispatch(setSelectedTag(null));
    dispatch(setSearchQuery(""));
  };

  const getActiveFilters = () => {
    const filters: string[] = [];

    if (searchQuery) {
      filters.push(`Поиск: "${searchQuery}"`);
    }

    if (selectedDate) {
      filters.push(`Дата: ${selectedDate}`);
    }

    if (selectedTag) {
      filters.push(`Тег: #${selectedTag}`);
    }

    return filters;
  };

  const activeFilters = getActiveFilters();

  const handleNoteSave = (noteId?: number | string) => {
    // Вызываем перезагрузку заметок после создания новой заметки
    if (notesListRef.current) {
      notesListRef.current.reloadNotes();
      // Устанавливаем фокус на сохраненную заметку после небольшой задержки,
      // чтобы дать время для перезагрузки и рендеринга заметок
      if (noteId) {
        let attempts = 0;
        const maxAttempts = 15;
        const attemptFocus = () => {
          attempts++;
          if (notesListRef.current) {
            // Проверяем, есть ли элемент заметки в DOM
            const noteElement = document.querySelector(
              `[data-note-id="${noteId}"]`
            );
            if (noteElement || attempts >= maxAttempts) {
              notesListRef.current.focusNote(noteId);
            } else if (attempts < maxAttempts) {
              // Пытаемся еще раз, если заметка еще не появилась в DOM
              setTimeout(attemptFocus, 100);
            }
          }
        };
        setTimeout(attemptFocus, 200);
      }
    }
  };

  const handleToggleMobileSidebar = () => {
    setIsMobileSidebarOpen(!isMobileSidebarOpen);
  };

  const handleCloseMobileSidebar = () => {
    setIsMobileSidebarOpen(false);
  };

  const handleNoteSelect = (noteId: number | string) => {
    setSelectedNoteIds((prev) => {
      if (prev.includes(noteId)) {
        return prev.filter((id) => id !== noteId);
      } else {
        return [...prev, noteId];
      }
    });
  };

  const handleMergeNotes = () => {
    if (selectedNoteIds.length < 2) {
      return;
    }
    setIsMergeModalOpen(true);
  };

  const handleMergeSuccess = () => {
    setSelectedNoteIds([]);
    if (notesListRef.current) {
      notesListRef.current.reloadNotes();
    }
  };

  const handleDeleteClick = () => {
    if (selectedNoteIds.length === 0) {
      return;
    }
    setIsDeleteModalOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (selectedNoteIds.length === 0) {
      return;
    }

    setIsDeleting(true);
    try {
      // Архивируем все выбранные заметки
      await Promise.all(
        selectedNoteIds.map((id) => offlineNotesApi.archive(id))
      );

      showNotification(
        `Архивировано заметок: ${selectedNoteIds.length}`,
        "success"
      );
      setSelectedNoteIds([]);
      setIsDeleteModalOpen(false);
      
      if (notesListRef.current) {
        notesListRef.current.reloadNotes();
      }
    } catch (error) {
      console.error("Ошибка архивирования заметок:", error);
      showNotification("Ошибка архивирования заметок", "error");
    } finally {
      setIsDeleting(false);
    }
  };

  const selectedNotes = notes.filter((note) =>
    selectedNoteIds.includes(note.id)
  );

  return (
    <>
      <MobileSidebar
        isOpen={isMobileSidebarOpen}
        onClose={handleCloseMobileSidebar}
      />
      <Sidebar notes={allNotes} />
      <div className="center">
        <div className="container">
          <Header onToggleSidebar={handleToggleMobileSidebar} />
          {hasFilters && (
            <div className="filter-indicator">
              <span className="filter-indicator-text">
                Фильтр: {activeFilters.join(", ")}
              </span>{" "}
              <button onClick={handleClearFilters}>✕</button>
            </div>
          )}
          {selectedNoteIds.length > 0 && (
            <div className="filter-indicator">
              <span className="filter-indicator-text">
                Выделено заметок: {selectedNoteIds.length}
              </span>{" "}
              <button
                onClick={() => setSelectedNoteIds([])}
                title="Снять выделение"
              >
                ✕
              </button>
            </div>
          )}
          <NoteEditor onSave={handleNoteSave} />
        </div>
        <NotesList
          ref={notesListRef}
          selectedNoteIds={selectedNoteIds}
          onNoteSelect={handleNoteSelect}
        />
      </div>
      {selectedNoteIds.length > 0 && (
        <div
          style={{
            position: "fixed",
            bottom: "20px",
            right: "20px",
            display: "flex",
            flexDirection: "column",
            gap: "12px",
            zIndex: 1000,
          }}
        >
          {selectedNoteIds.length >= 2 && aiEnabled && (
            <button
              onClick={handleMergeNotes}
              style={{
                width: "56px",
                height: "56px",
                borderRadius: "50%",
                backgroundColor:
                  theme === "dark" ? "#4CAF50" : "#2196F3",
                color: "white",
                border: "none",
                cursor: "pointer",
                boxShadow:
                  theme === "dark"
                    ? "0 4px 12px rgba(76, 175, 80, 0.4)"
                    : "0 4px 12px rgba(33, 150, 243, 0.4)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                fontSize: "24px",
                transition: "all 0.3s ease",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = "scale(1.1)";
                e.currentTarget.style.boxShadow =
                  theme === "dark"
                    ? "0 6px 16px rgba(76, 175, 80, 0.6)"
                    : "0 6px 16px rgba(33, 150, 243, 0.6)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = "scale(1)";
                e.currentTarget.style.boxShadow =
                  theme === "dark"
                    ? "0 4px 12px rgba(76, 175, 80, 0.4)"
                    : "0 4px 12px rgba(33, 150, 243, 0.4)";
              }}
              title={`Объединить ${selectedNoteIds.length} заметок`}
            >
              <Icon icon="mdi:link-variant" />
            </button>
          )}
          <button
            onClick={handleDeleteClick}
            disabled={isDeleting}
            style={{
              width: "56px",
              height: "56px",
              borderRadius: "50%",
              backgroundColor: theme === "dark" ? "#FF9800" : "#FF9800",
              color: "white",
              border: "none",
              cursor: isDeleting ? "not-allowed" : "pointer",
              opacity: isDeleting ? 0.6 : 1,
              boxShadow:
                theme === "dark"
                  ? "0 4px 12px rgba(255, 152, 0, 0.4)"
                  : "0 4px 12px rgba(255, 152, 0, 0.4)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "24px",
              transition: "all 0.3s ease",
            }}
            onMouseEnter={(e) => {
              if (!isDeleting) {
                e.currentTarget.style.transform = "scale(1.1)";
                e.currentTarget.style.boxShadow =
                  theme === "dark"
                    ? "0 6px 16px rgba(255, 152, 0, 0.6)"
                    : "0 6px 16px rgba(255, 152, 0, 0.6)";
              }
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = "scale(1)";
              e.currentTarget.style.boxShadow =
                theme === "dark"
                  ? "0 4px 12px rgba(255, 152, 0, 0.4)"
                  : "0 4px 12px rgba(255, 152, 0, 0.4)";
            }}
            title={`Архивировать ${selectedNoteIds.length} ${selectedNoteIds.length === 1 ? "заметку" : selectedNoteIds.length > 4 ? "заметок" : "заметки"}`}
          >
            <Icon icon="mdi:archive" />
          </button>
        </div>
      )}
      <ImageModal />
      <MergeNotesModal
        isOpen={isMergeModalOpen}
        onClose={() => setIsMergeModalOpen(false)}
        selectedNotes={selectedNotes}
        onSuccess={handleMergeSuccess}
      />
      <Modal
        isOpen={isDeleteModalOpen}
        onClose={() => setIsDeleteModalOpen(false)}
        onConfirm={handleDeleteConfirm}
        title="Архивирование заметок"
        message={
          <p>
            Вы уверены, что хотите архивировать{" "}
            <strong>{selectedNoteIds.length}</strong>{" "}
            {selectedNoteIds.length === 1
              ? "заметку"
              : selectedNoteIds.length > 4
              ? "заметок"
              : "заметки"}
            ? Заметки можно будет восстановить из архива в настройках.
          </p>
        }
        confirmText={isDeleting ? "Архивирование..." : "Архивировать"}
        cancelText="Отмена"
        confirmType="primary"
      />
    </>
  );
};

export default NotesPage;
