import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import json
import random


class TangPoetryApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Tang Poetry 300")
        self.root.geometry("900x600")

        self.poems = self.load_poems()
        self.setup_ui()

    def load_poems(self):
        poems_data = [
            {
                "id": 1,
                "title": "Jing Ye Si",
                "author": "Li Bai",
                "dynasty": "Tang",
                "content": "Chuang qian ming yue guang,\nYi shi di shang shuang.\nJu tou wang ming yue,\nDi tou si gu xiang.",
                "tags": ["Homesick", "Moon", "Lyric"],
                "translation": "Bright moonlight before my bed,\nPerhaps frost on the ground.\nRaising my head, I see the moon bright,\nLowering it, I miss my hometown."
            },
            {
                "id": 2,
                "title": "Chun Xiao",
                "author": "Meng Haoran",
                "dynasty": "Tang",
                "content": "Chun mian bu jue xiao,\nChu chu wen ti niao.\nYe lai feng yu sheng,\nHua luo zhi duo shao.",
                "tags": ["Spring", "Scenery", "Lyric"],
                "translation": "I slept in spring not conscious of the dawn,\nTill I heard birds everywhere singing.\nLast night I heard the sound of wind and rain,\nHow many blossoms have fallen?"
            },
            {
                "id": 3,
                "title": "Deng Guan Que Lou",
                "author": "Wang Zhihuan",
                "dynasty": "Tang",
                "content": "Bai ri yi shan jin,\nHuang he ru hai liu.\nYu qiong qian li mu,\nGeng shang yi ceng lou.",
                "tags": ["Scenery", "Philosophy", "Inspirational"],
                "translation": "The sun along the mountain bows,\nThe Yellow River seawards flows.\nTo have a good view far and nigh,\nYou will mount a storey high."
            }
        ]
        return poems_data

    def setup_ui(self):
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(2, weight=1)

        title_label = ttk.Label(
            main_frame,
            text="Tang Poetry 300",
            font=("Arial", 24, "bold"),
            foreground="#8B4513"
        )
        title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))

        search_frame = ttk.Frame(main_frame)
        search_frame.grid(row=1, column=0, columnspan=3,
                          sticky=(tk.W, tk.E), pady=(0, 10))

        ttk.Label(search_frame, text="Search:").pack(side=tk.LEFT, padx=(0, 5))

        self.search_var = tk.StringVar()
        self.search_entry = ttk.Entry(
            search_frame, textvariable=self.search_var, width=40)
        self.search_entry.pack(side=tk.LEFT, padx=(0, 10))
        self.search_entry.bind("<KeyRelease>", self.on_search)

        search_btn = ttk.Button(
            search_frame, text="Search", command=self.on_search)
        search_btn.pack(side=tk.LEFT, padx=(0, 10))

        random_btn = ttk.Button(
            search_frame, text="Random Poem", command=self.show_random_poem)
        random_btn.pack(side=tk.LEFT)

        list_frame = ttk.LabelFrame(main_frame, text="Poem List", padding="5")
        list_frame.grid(row=2, column=0, sticky=(
            tk.W, tk.E, tk.N, tk.S), padx=(0, 10))

        self.poem_listbox = tk.Listbox(
            list_frame,
            width=30,
            height=20,
            font=("Arial", 11)
        )
        self.poem_listbox.pack(fill=tk.BOTH, expand=True)

        self.poem_listbox.bind('<<ListboxSelect>>', self.on_poem_select)

        list_scrollbar = ttk.Scrollbar(self.poem_listbox, orient=tk.VERTICAL)
        list_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.poem_listbox.config(yscrollcommand=list_scrollbar.set)
        list_scrollbar.config(command=self.poem_listbox.yview)

        detail_frame = ttk.LabelFrame(
            main_frame, text="Poem Details", padding="10")
        detail_frame.grid(row=2, column=1, sticky=(tk.W, tk.E, tk.N, tk.S))

        self.title_label = ttk.Label(
            detail_frame,
            text="",
            font=("Arial", 18, "bold"),
            foreground="#8B0000"
        )
        self.title_label.grid(row=0, column=0, columnspan=2, pady=(0, 10))

        self.author_label = ttk.Label(
            detail_frame,
            text="",
            font=("Arial", 12),
            foreground="#556B2F"
        )
        self.author_label.grid(row=1, column=0, sticky=tk.W, pady=(0, 5))

        self.tags_label = ttk.Label(
            detail_frame,
            text="",
            font=("Arial", 10),
            foreground="#696969"
        )
        self.tags_label.grid(row=1, column=1, sticky=tk.E, pady=(0, 5))

        separator = ttk.Separator(detail_frame, orient='horizontal')
        separator.grid(row=2, column=0, columnspan=2,
                       sticky=(tk.W, tk.E), pady=10)

        content_frame = ttk.Frame(detail_frame)
        content_frame.grid(row=3, column=0, columnspan=2,
                           sticky=(tk.W, tk.E, tk.N, tk.S))

        self.content_text = scrolledtext.ScrolledText(
            content_frame,
            width=50,
            height=8,
            font=("Arial", 14),
            wrap=tk.WORD,
            bg="#FFF8DC"
        )
        self.content_text.pack(fill=tk.BOTH, expand=True)

        ttk.Label(detail_frame, text="Translation:", font=("Arial", 11, "bold")).grid(
            row=4, column=0, sticky=tk.W, pady=(15, 5)
        )

        self.translation_text = scrolledtext.ScrolledText(
            detail_frame,
            width=50,
            height=5,
            font=("Arial", 11),
            wrap=tk.WORD
        )
        self.translation_text.grid(
            row=5, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S))

        self.status_bar = ttk.Label(
            main_frame,
            text=f"Total {len(self.poems)} poems",
            relief=tk.SUNKEN
        )
        self.status_bar.grid(row=3, column=0, columnspan=2,
                             sticky=(tk.W, tk.E), pady=(10, 0))

        detail_frame.columnconfigure(0, weight=1)
        detail_frame.columnconfigure(1, weight=1)
        detail_frame.rowconfigure(5, weight=1)

        self.update_poem_list(self.poems)

    def update_poem_list(self, poems):
        self.poem_listbox.delete(0, tk.END)
        for poem in poems:
            display_text = f"{poem['title']} - {poem['author']}"
            self.poem_listbox.insert(tk.END, display_text)

        self.status_bar.config(text=f"Found {len(poems)} poems")

    def on_search(self, event=None):
        keyword = self.search_var.get().strip().lower()

        if not keyword:
            filtered_poems = self.poems
        else:
            filtered_poems = []
            for poem in self.poems:
                if (keyword in poem['title'].lower() or
                    keyword in poem['author'].lower() or
                    keyword in poem['content'].lower() or
                        any(keyword in tag.lower() for tag in poem.get('tags', []))):
                    filtered_poems.append(poem)

        self.update_poem_list(filtered_poems)

        if filtered_poems:
            self.poem_listbox.selection_set(0)
            self.display_poem_details(filtered_poems[0])

    def on_poem_select(self, event):
        selection = self.poem_listbox.curselection()
        if selection:
            index = selection[0]
            keyword = self.search_var.get().strip().lower()

            if keyword:
                filtered_poems = []
                for poem in self.poems:
                    if (keyword in poem['title'].lower() or
                        keyword in poem['author'].lower() or
                        keyword in poem['content'].lower() or
                            any(keyword in tag.lower() for tag in poem.get('tags', []))):
                        filtered_poems.append(poem)
                if index < len(filtered_poems):
                    self.display_poem_details(filtered_poems[index])
            else:
                if index < len(self.poems):
                    self.display_poem_details(self.poems[index])

    def display_poem_details(self, poem):
        self.content_text.delete(1.0, tk.END)
        self.translation_text.delete(1.0, tk.END)

        self.title_label.config(text=poem['title'])
        self.author_label.config(text=f"{poem['author']} ({poem['dynasty']})")

        tags = poem.get('tags', [])
        tags_text = "Tags: " + ", ".join(tags) if tags else ""
        self.tags_label.config(text=tags_text)

        self.content_text.insert(1.0, poem['content'])
        self.content_text.config(state='disabled')

        translation = poem.get('translation', 'No translation available')
        self.translation_text.insert(1.0, translation)
        self.translation_text.config(state='disabled')

    def show_random_poem(self):
        if self.poems:
            random_poem = random.choice(self.poems)

            self.search_var.set("")
            self.update_poem_list(self.poems)

            for i, poem in enumerate(self.poems):
                if poem['id'] == random_poem['id']:
                    self.poem_listbox.selection_clear(0, tk.END)
                    self.poem_listbox.selection_set(i)
                    self.poem_listbox.see(i)
                    break

            self.display_poem_details(random_poem)
            self.status_bar.config(
                text=f"Random: {random_poem['title']} - {random_poem['author']}")


def main():
    root = tk.Tk()
    app = TangPoetryApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()
