"""
絵文字選択ダイアログモジュール
ショートカット設定とメモ挿入の両方で使用可能
"""

from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                             QPushButton, QComboBox, QScrollArea, QWidget, QGridLayout)
from PyQt5.QtCore import Qt
from app_utils import get_translation

class EmojiSelectionDialog(QDialog):
    """絵文字選択用のカスタムダイアログ"""
    
    def __init__(self, parent, shortcut_index=None, for_memo_insert=False):
        super().__init__(parent)
        self.shortcut_index = shortcut_index
        self.for_memo_insert = for_memo_insert
        self.selected_emoji = None
        
        # 大幅に拡張した絵文字リスト（300個以上）
        # キーは翻訳キー、値は絵文字リスト
        self.emoji_data = {
            "emoji_category_faces": ["😀", "😃", "😄", "😁", "😆", "😅", "🤣", "😂", "🙂", "🙃", "🫠", "😉", "😊", "😇", "🥰", "😍", "🤩", "😘", "😗", "☺️", "😚", "😙", "🥲", "😋", "😛", "😜", "🤪", "😝", "🤑", "🤗"],
            "emoji_category_activities": ["🚀", "⭐", "🔥", "💎", "🎯", "🏆", "🥇", "🥈", "🥉", "🏅", "🎖️", "⚽", "🏀", "🏈", "⚾", "🥎", "🎾", "🏐", "🏉", "🥏", "🎱", "🪀", "🏓", "🏸", "🏒", "🏑", "🥍", "🏏", "🪃", "🥅"],
            "emoji_category_arts": ["🎨", "🎭", "🎪", "🎬", "🎤", "🎧", "🎼", "🎵", "🎶", "🎹", "🥁", "🪘", "🎷", "🎺", "🪗", "🎸", "🪕", "🎻", "🎲", "♠️", "♥️", "♦️", "♣️", "♟️", "🃏", "🀄", "🎴", "🎮", "🕹️", "🎰"],
            "emoji_category_technology": ["💻", "🖥️", "🖨️", "⌨️", "🖱️", "🖲️", "💽", "💾", "💿", "📀", "📱", "📞", "☎️", "📟", "📠", "📺", "📻", "🎙️", "⏱️", "⏲️", "⏰", "🕰️", "📡", "🔋", "🪫", "🔌", "💡", "🔦", "🕯️", "🪔"],
            "emoji_category_education": ["📚", "📖", "📗", "📘", "📙", "📕", "📓", "📔", "📒", "📃", "📄", "📰", "📑", "🔖", "🏷️", "💰", "🪙", "💴", "💵", "💶", "💷", "💸", "💳", "🧾", "💎", "⚖️", "🪜", "🔧", "🔨", "⚒️"],
            "emoji_category_nature": ["🌈", "🌟", "✨", "⭐", "🌠", "🌙", "☀️", "🌞", "🪐", "🌍", "🌎", "🌏", "🌕", "🌖", "🌗", "🌘", "🌑", "🌒", "🌓", "🌔", "🌚", "🌝", "🌛", "🌜", "☁️", "⛅", "⛈️", "🌤️", "🌦️", "🌧️"],
            "emoji_category_plants": ["🌸", "🌺", "🌻", "🌷", "🌹", "🥀", "🌼", "🌲", "🌳", "🌴", "🌵", "🌶️", "🍄", "🌾", "💐", "🎋", "🎍", "🍀", "🍃", "🍂", "🍁", "🌿", "🪴", "🪸", "🪷", "💮", "🏵️", "🌱", "☘️", "🎄"],
            "emoji_category_food": ["🍎", "🍏", "🍊", "🍋", "🍌", "🍉", "🍇", "🍓", "🫐", "🍈", "🍒", "🍑", "🥭", "🍍", "🥥", "🥝", "🍅", "🍆", "🥑", "🥦", "🥒", "🌶️", "🫑", "🌽", "🥕", "🧄", "🧅", "🥔", "🍠", "🫘"],
            "emoji_category_symbols": ["⚡", "🔥", "💫", "⭐", "🌟", "✨", "💥", "💢", "💯", "💊", "🎊", "🎉", "🎈", "🎁", "🎀", "🪅", "🪩", "🧿", "🪬", "🔮", "🪄", "🎪", "🎭", "🖼️", "🎨", "🧵", "🪡", "🧶", "🪢", "🎂"],
            "emoji_category_hearts": ["❤️", "🧡", "💛", "💚", "💙", "💜", "🖤", "🤍", "🤎", "💔", "❤️‍🔥", "❤️‍🩹", "💕", "💞", "💓", "💗", "💖", "💘", "💝", "💟", "♥️", "💌", "💋", "💍", "👑", "💎", "🌹", "💐", "🎀", "🎁"]
        }
        
        # 翻訳されたカテゴリー名で辞書を作成
        self.emoji_categories = {}
        for key, emojis in self.emoji_data.items():
            translated_name = get_translation(key)
            self.emoji_categories[translated_name] = emojis
        
        # タイトル設定
        if self.for_memo_insert:
            title = get_translation("emoji_selection_title")
        else:
            title = f"ショートカット {shortcut_index} の絵文字選択"
        
        self.setWindowTitle(title)
        self.setModal(True)
        self.setAttribute(Qt.WA_QuitOnClose, False)
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.resize(500, 600)  # より大きなサイズ
        
        self.setup_ui()
    
    def setup_ui(self):
        """UI設定"""
        layout = QVBoxLayout()
        
        # 説明ラベル
        if self.for_memo_insert:
            description = get_translation("emoji_selection_description")
        else:
            description = f"ショートカット {self.shortcut_index} に使用する絵文字を選択してください："
            
        info_label = QLabel(description)
        info_label.setWordWrap(True)
        layout.addWidget(info_label)
        
        # カテゴリ選択用のコンボボックス
        category_label = QLabel(get_translation("emoji_category_label"))
        layout.addWidget(category_label)
        
        self.category_combo = QComboBox()
        self.category_combo.addItems(list(self.emoji_categories.keys()))
        self.category_combo.currentTextChanged.connect(self.update_emoji_grid)
        layout.addWidget(self.category_combo)
        
        # 絵文字表示用のスクロールエリア
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setMinimumHeight(400)
        
        self.emoji_widget = QWidget()
        self.emoji_layout = QGridLayout(self.emoji_widget)
        
        scroll_area.setWidget(self.emoji_widget)
        layout.addWidget(scroll_area)
        
        # 選択された絵文字の表示
        selection_layout = QHBoxLayout()
        selection_layout.addWidget(QLabel(get_translation("emoji_selected_label")))
        
        self.selected_label = QLabel(get_translation("emoji_none_selected"))
        self.selected_label.setStyleSheet("font-size: 24px; border: 1px solid gray; padding: 5px; min-width: 40px; text-align: center;")
        self.selected_label.setAlignment(Qt.AlignCenter)
        selection_layout.addWidget(self.selected_label)
        selection_layout.addStretch()
        layout.addLayout(selection_layout)
        
        # ボタン
        button_layout = QHBoxLayout()
        
        ok_button = QPushButton("OK")
        ok_button.clicked.connect(self.accept)
        ok_button.setEnabled(False)  # 初期状態では無効
        self.ok_button = ok_button
        
        cancel_button = QPushButton(get_translation("message_cancel_title"))
        cancel_button.clicked.connect(self.reject)
        
        clear_button = QPushButton(get_translation("emoji_clear_button"))
        clear_button.clicked.connect(self.clear_selection)
        
        button_layout.addWidget(clear_button)
        button_layout.addStretch()
        button_layout.addWidget(cancel_button)
        button_layout.addWidget(ok_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
        
        # 初期カテゴリを表示
        self.update_emoji_grid()
    
    def update_emoji_grid(self):
        """選択されたカテゴリの絵文字を表示"""
        # 既存のボタンをクリア
        for i in reversed(range(self.emoji_layout.count())):
            self.emoji_layout.itemAt(i).widget().deleteLater()
        
        current_category = self.category_combo.currentText()
        if current_category not in self.emoji_categories:
            return
        
        emojis = self.emoji_categories[current_category]
        
        # グリッドレイアウトで絵文字ボタンを配置（1行に8個）
        cols = 8
        for i, emoji in enumerate(emojis):
            row = i // cols
            col = i % cols
            
            button = QPushButton(emoji)
            button.setFixedSize(50, 50)  # 正方形のボタン
            button.setStyleSheet("""
                QPushButton {
                    font-size: 24px;
                    border: 2px solid #cccccc;
                    border-radius: 8px;
                    background-color: white;
                    padding: 5px;
                }
                QPushButton:hover {
                    border-color: #007acc;
                    background-color: #f0f8ff;
                }
                QPushButton:pressed {
                    background-color: #e0e0e0;
                }
            """)
            button.clicked.connect(lambda checked, e=emoji: self.select_emoji(e))
            
            self.emoji_layout.addWidget(button, row, col)
    
    def select_emoji(self, emoji):
        """絵文字を選択"""
        self.selected_emoji = emoji
        self.selected_label.setText(emoji)
        self.selected_label.setStyleSheet("font-size: 24px; border: 2px solid #007acc; background-color: #f0f8ff; padding: 5px; min-width: 40px; text-align: center;")
        self.ok_button.setEnabled(True)
    
    def clear_selection(self):
        """選択をクリア"""
        self.selected_emoji = None
        self.selected_label.setText(get_translation("emoji_none_selected"))
        self.selected_label.setStyleSheet("font-size: 24px; border: 1px solid gray; padding: 5px; min-width: 40px; text-align: center;")
        self.ok_button.setEnabled(False)
    
    def get_selected_emoji(self):
        """選択された絵文字を取得"""
        return self.selected_emoji