import json
import os
import tkinter as tk
from datetime import datetime
from tkinter import messagebox, ttk

TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
DISPLAY_FORMAT = "%d.%m.%Y %H:%M:%S"
PREVIEW_LIMIT = 90


def current_time_string():
    return datetime.now().strftime(TIME_FORMAT)


def display_time(value):
    try:
        return datetime.strptime(value, TIME_FORMAT).strftime(DISPLAY_FORMAT)
    except (TypeError, ValueError):
        return str(value)


def make_preview(text):
    line = " ".join(text.split())
    if len(line) > PREVIEW_LIMIT:
        return line[: PREVIEW_LIMIT - 3] + "..."
    return line


def notes_file_path():
    if os.name == "nt":
        base = os.environ.get("APPDATA") or os.path.expanduser("~")
    else:
        base = os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share")
    return os.path.join(base, "ShortNotes", "notes.json")


class NotesApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Короткие заметки")
        self.geometry("940x580")
        self.minsize(720, 440)

        self.storage_path = notes_file_path()
        self.notes = []
        self.current_id = None
        self.suspend_select = False
        self.loading_list = False

        self._build_ui()
        self._load_notes()
        self._refresh_list()
        self._update_info()
        self._update_status()

        self.protocol("WM_DELETE_WINDOW", self._on_close)
        self.bind_all("<Control-s>", self._on_shortcut_save)
        self.bind_all("<Control-n>", self._on_shortcut_new)
        self.text.focus_set()

    def _build_ui(self):
        self.status_var = tk.StringVar(master=self)
        ttk.Label(self, textvariable=self.status_var, anchor="w", padding=(8, 4)).pack(side="bottom", fill="x")

        main = ttk.Frame(self, padding=8)
        main.pack(fill="both", expand=True)

        search_bar = ttk.Frame(main)
        search_bar.pack(fill="x", pady=(0, 8))
        ttk.Label(search_bar, text="Поиск:").pack(side="left")
        self.search_var = tk.StringVar(master=self)
        ttk.Entry(search_bar, textvariable=self.search_var).pack(side="left", fill="x", expand=True, padx=6)
        ttk.Button(search_bar, text="Сбросить", command=self._reset_search).pack(side="left")

        paned = ttk.Panedwindow(main, orient="horizontal")
        paned.pack(fill="both", expand=True)

        left = ttk.Frame(paned, padding=(0, 0, 6, 0))
        right = ttk.Frame(paned, padding=(6, 0, 0, 0))
        paned.add(left, weight=2)
        paned.add(right, weight=3)

        tree_frame = ttk.Frame(left)
        tree_frame.pack(fill="both", expand=True)
        self.tree = ttk.Treeview(tree_frame, columns=("created", "preview"), show="headings", selectmode="browse")
        self.tree.heading("created", text="Дата и время")
        self.tree.heading("preview", text="Заметка")
        self.tree.column("created", width=150, minwidth=130, stretch=False, anchor="w")
        self.tree.column("preview", width=220, minwidth=120, stretch=True, anchor="w")
        tree_scroll = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=tree_scroll.set)
        self.tree.pack(side="left", fill="both", expand=True)
        tree_scroll.pack(side="right", fill="y")
        self.tree.bind("<<TreeviewSelect>>", self._on_select)
        self.tree.bind("<Delete>", self._on_tree_delete)

        self.info_var = tk.StringVar(master=self, value="Новая заметка")
        ttk.Label(right, textvariable=self.info_var).pack(fill="x", pady=(0, 6))

        text_frame = ttk.Frame(right)
        text_frame.pack(fill="both", expand=True)
        self.text = tk.Text(text_frame, wrap="word", undo=True, font=("Segoe UI", 10))
        text_scroll = ttk.Scrollbar(text_frame, orient="vertical", command=self.text.yview)
        self.text.configure(yscrollcommand=text_scroll.set)
        self.text.pack(side="left", fill="both", expand=True)
        text_scroll.pack(side="right", fill="y")

        buttons = ttk.Frame(right)
        buttons.pack(fill="x", pady=(8, 0))
        ttk.Button(buttons, text="Новая", command=self._new_note).pack(side="left")
        ttk.Button(buttons, text="Сохранить", command=self._save).pack(side="left", padx=6)
        ttk.Button(buttons, text="Удалить", command=self._delete).pack(side="left")

        self.search_var.trace_add("write", self._on_search_changed)

    def _on_search_changed(self, *args):
        self._refresh_list()

    def _reset_search(self):
        self.search_var.set("")

    def _on_shortcut_save(self, event):
        self._save()
        return "break"

    def _on_shortcut_new(self, event):
        self._new_note()
        return "break"

    def _on_tree_delete(self, event):
        self._delete()
        return "break"

    def _load_notes(self):
        self.notes = []
        if not os.path.exists(self.storage_path):
            return
        try:
            with open(self.storage_path, "r", encoding="utf-8") as handle:
                data = json.load(handle)
        except (OSError, ValueError) as exc:
            messagebox.showerror("Ошибка чтения", f"Не удалось прочитать файл заметок:\n{exc}", parent=self)
            return
        if not isinstance(data, list):
            messagebox.showerror("Ошибка чтения", "Файл заметок имеет неверный формат.", parent=self)
            return
        result = []
        seen = set()
        for item in data:
            if not isinstance(item, dict):
                continue
            note_id = item.get("id")
            created = item.get("created")
            text = item.get("text")
            if isinstance(note_id, bool) or not isinstance(note_id, int):
                continue
            if not isinstance(created, str) or not isinstance(text, str):
                continue
            if note_id in seen:
                continue
            seen.add(note_id)
            updated = item.get("updated")
            if not isinstance(updated, str):
                updated = created
            result.append({"id": note_id, "created": created, "updated": updated, "text": text})
        self.notes = result

    def _save_file(self):
        try:
            folder = os.path.dirname(self.storage_path)
            os.makedirs(folder, exist_ok=True)
            temp_path = self.storage_path + ".tmp"
            with open(temp_path, "w", encoding="utf-8") as handle:
                json.dump(self.notes, handle, ensure_ascii=False, indent=2)
            os.replace(temp_path, self.storage_path)
        except (OSError, TypeError, ValueError) as exc:
            messagebox.showerror("Ошибка сохранения", f"Не удалось сохранить заметки:\n{exc}", parent=self)
            return False
        return True

    def _refresh_list(self):
        query = self.search_var.get().strip().lower()
        self.loading_list = True
        try:
            children = self.tree.get_children()
            if children:
                self.tree.delete(*children)
            for note in sorted(self.notes, key=lambda item: (item["created"], item["id"]), reverse=True):
                if query and query not in note["text"].lower():
                    continue
                self.tree.insert(
                    "",
                    "end",
                    iid=str(note["id"]),
                    values=(display_time(note["created"]), make_preview(note["text"])),
                )
            if self.current_id is not None:
                iid = str(self.current_id)
                if self.tree.exists(iid):
                    self.tree.selection_set(iid)
                    self.tree.focus(iid)
                    self.tree.see(iid)
        finally:
            self.loading_list = False

    def _find(self, note_id):
        for note in self.notes:
            if note["id"] == note_id:
                return note
        return None

    def _next_id(self):
        return max((note["id"] for note in self.notes), default=0) + 1

    def _editor_text(self):
        return self.text.get("1.0", "end-1c")

    def _set_editor_text(self, value):
        self.text.delete("1.0", "end")
        if value:
            self.text.insert("1.0", value)
        self.text.edit_reset()

    def _is_dirty(self):
        text = self._editor_text()
        if self.current_id is None:
            return bool(text.strip())
        note = self._find(self.current_id)
        if note is None:
            return bool(text.strip())
        return note["text"] != text

    def _on_select(self, event=None):
        if self.loading_list or self.suspend_select:
            return
        selection = self.tree.selection()
        if not selection:
            return
        try:
            new_id = int(selection[0])
        except ValueError:
            return
        if new_id == self.current_id:
            return
        if not self._confirm_pending():
            self.suspend_select = True
            try:
                if self.current_id is not None and self.tree.exists(str(self.current_id)):
                    iid = str(self.current_id)
                    self.tree.selection_set(iid)
                    self.tree.focus(iid)
                    self.tree.see(iid)
                else:
                    selected = self.tree.selection()
                    if selected:
                        self.tree.selection_remove(selected)
            finally:
                self.suspend_select = False
            return
        self._show_note(new_id)

    def _confirm_pending(self):
        if not self._is_dirty():
            return True
        if not self._editor_text().strip():
            return True
        answer = messagebox.askyesnocancel(
            "Несохранённые изменения",
            "Сохранить изменения в текущей заметке?",
            parent=self,
        )
        if answer is None:
            return False
        if not answer:
            return True
        return self._store_editor()

    def _store_editor(self):
        text = self._editor_text()
        if not text.strip():
            messagebox.showerror("Ошибка", "Текст заметки не может быть пустым.", parent=self)
            return False
        stamp = current_time_string()
        if self.current_id is None:
            new_note = {"id": self._next_id(), "created": stamp, "updated": stamp, "text": text}
            self.notes.append(new_note)
            self.current_id = new_note["id"]
            if not self._save_file():
                self.notes.pop()
                self.current_id = None
                return False
        else:
            note = self._find(self.current_id)
            if note is None:
                messagebox.showerror("Ошибка", "Заметка не найдена.", parent=self)
                return False
            if note["text"] == text:
                self._update_info()
                self._update_status()
                return True
            previous_text = note["text"]
            previous_updated = note["updated"]
            note["text"] = text
            note["updated"] = stamp
            if not self._save_file():
                note["text"] = previous_text
                note["updated"] = previous_updated
                return False
        self._refresh_list()
        self._update_info()
        self._update_status()
        return True

    def _show_note(self, note_id):
        note = self._find(note_id) if note_id is not None else None
        if note is None:
            self.current_id = None
            self._set_editor_text("")
        else:
            self.current_id = note["id"]
            self._set_editor_text(note["text"])
        self._update_info()
        self._update_status()
        self.suspend_select = True
        try:
            if self.current_id is not None and self.tree.exists(str(self.current_id)):
                iid = str(self.current_id)
                self.tree.selection_set(iid)
                self.tree.focus(iid)
                self.tree.see(iid)
            else:
                selected = self.tree.selection()
                if selected:
                    self.tree.selection_remove(selected)
        finally:
            self.suspend_select = False

    def _new_note(self):
        if not self._confirm_pending():
            return
        self.current_id = None
        self.suspend_select = True
        try:
            selected = self.tree.selection()
            if selected:
                self.tree.selection_remove(selected)
        finally:
            self.suspend_select = False
        self._set_editor_text("")
        self._update_info()
        self._update_status()
        self.text.focus_set()

    def _save(self):
        self._store_editor()
        self.text.focus_set()

    def _delete(self):
        if self.current_id is None:
            messagebox.showerror("Ошибка", "Сначала выберите заметку для удаления.", parent=self)
            return
        note = self._find(self.current_id)
        if note is None:
            messagebox.showerror("Ошибка", "Заметка не найдена.", parent=self)
            return
        if not messagebox.askyesno("Удаление", "Удалить выбранную заметку?", parent=self):
            return
        backup = list(self.notes)
        removed_id = self.current_id
        self.notes = [item for item in self.notes if item["id"] != removed_id]
        if not self._save_file():
            self.notes = backup
            return
        self.current_id = None
        self.suspend_select = True
        try:
            selected = self.tree.selection()
            if selected:
                self.tree.selection_remove(selected)
        finally:
            self.suspend_select = False
        self._set_editor_text("")
        self._refresh_list()
        self._update_info()
        self._update_status()

    def _update_info(self):
        note = self._find(self.current_id) if self.current_id is not None else None
        if note is None:
            self.info_var.set("Новая заметка")
            return
        text = f"Создана: {display_time(note['created'])}"
        updated = note.get("updated") or note["created"]
        if updated != note["created"]:
            text += f"    Изменена: {display_time(updated)}"
        self.info_var.set(text)

    def _update_status(self):
        self.status_var.set(f"Заметок: {len(self.notes)}    Файл: {self.storage_path}")

    def _on_close(self):
        if self._confirm_pending():
            self.destroy()


def main():
    app = NotesApp()
    app.mainloop()


if __name__ == "__main__":
    main()