import json
import logging
from pathlib import Path
from typing import Dict, Any, Optional, Tuple
from PyQt6.QtWidgets import (
    QDialog, QFormLayout, QLineEdit, QPushButton,
    QColorDialog, QDialogButtonBox, QMessageBox, QApplication, QStyleFactory
)
from PyQt6.QtGui import QColor
from core.config import get_app_data_directory, CUSTOM_THEMES_FILE, APP_THEMES, RESOURCES_DIR, logger
from core.db import SettingsManager
class CustomThemeManager:
    """Handles loading and saving of user-created themes."""
    def __init__(self):
        self.themes_file = Path(get_app_data_directory()) / CUSTOM_THEMES_FILE
        self.custom_themes: Dict[str, Any] = self._load_themes()
    def _load_themes(self) -> Dict[str, Any]:
        if not self.themes_file.exists():
            return {}
        try:
            with open(self.themes_file, "r", encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, Exception) as e:
            logger.error(f"Failed to load custom themes file: {e}")
            return {}
    def _save_all_themes(self):
        try:
            with open(self.themes_file, "w", encoding='utf-8') as f:
                json.dump(self.custom_themes, f, indent=4)
        except Exception as e:
            logger.error(f"Failed to save custom themes: {e}")
    def save_theme(self, name: str, theme_data: Dict[str, str]):
        self.custom_themes[name] = theme_data
        self._save_all_themes()
    def delete_theme(self, name: str):
        if name in self.custom_themes:
            del self.custom_themes[name]
            self._save_all_themes()
    def get_themes(self) -> Dict[str, Any]:
        return self.custom_themes
class CreateThemeDialog(QDialog):
    """Dialog for creating a new custom theme."""
    def __init__(self, lang, parent=None, name="", theme_data=None):
        super().__init__(parent)
        self.lang = lang
        self.setWindowTitle(self.lang["new_theme_creator"])
        self.setMinimumWidth(400)
        layout = QFormLayout(self)
        self.theme_name_edit = QLineEdit(name)
        layout.addRow(f'{self.lang["theme_name"]}:', self.theme_name_edit)
        defaults = {
            "primary": "#285430", "secondary": "#5F8D4E", "background": "#F1F8E9",
            "text_dark": "#000000", "text_light": "#FFFFFF", "danger": "#D32F2F", "warning": "#FFC107"
        }
        if theme_data: defaults.update(theme_data)
        self.primary_btn, self.primary_color = self._create_color_button(defaults["primary"])
        layout.addRow(f'{self.lang["primary_color"]}:', self.primary_btn)
        self.secondary_btn, self.secondary_color = self._create_color_button(defaults["secondary"])
        layout.addRow(f'{self.lang["secondary_color"]}:', self.secondary_btn)
        self.background_btn, self.background_color = self._create_color_button(defaults["background"])
        layout.addRow(f'{self.lang["background_color"]}:', self.background_btn)
        self.text_dark_btn, self.text_dark_color = self._create_color_button(defaults["text_dark"])
        layout.addRow(f'{self.lang["text_color_dark"]}:', self.text_dark_btn)
        self.text_light_btn, self.text_light_color = self._create_color_button(defaults["text_light"])
        layout.addRow(f'{self.lang["text_color_light"]}:', self.text_light_btn)
        self.danger_btn, self.danger_color = self._create_color_button(defaults["danger"])
        layout.addRow(f'{self.lang["danger_color"]}:', self.danger_btn)
        self.warning_btn, self.warning_color = self._create_color_button(defaults["warning"])
        layout.addRow(f'{self.lang["warning_color"]}:', self.warning_btn)
        self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        ok_btn = self.buttons.button(QDialogButtonBox.StandardButton.Ok)
        if ok_btn:
            ok_btn.setDefault(True)
            ok_btn.setAutoDefault(True)
        self.theme_name_edit.returnPressed.connect(self.accept)
        layout.addRow(self.buttons)
    def _create_color_button(self, default_color_hex: str) -> Tuple[QPushButton, QColor]:
        color = QColor(default_color_hex)
        button = QPushButton(default_color_hex)
        button.setStyleSheet(f"background-color: {color.name()}; color: {'black' if color.lightness() > 127 else 'white'};")
        button.clicked.connect(lambda ch, b=button, c=color: self._pick_color(b, c))
        return button, color
    def _pick_color(self, button: QPushButton, color_obj: QColor):
        new_color = QColorDialog.getColor(color_obj, self)
        if new_color.isValid():
            color_obj.setNamedColor(new_color.name())
            button.setText(new_color.name())
            button.setStyleSheet(f"background-color: {new_color.name()}; color: {'black' if new_color.lightness() > 127 else 'white'};")
    def get_theme_data(self) -> Optional[Dict[str, Any]]:
        name = self.theme_name_edit.text().strip()
        if not name:
            QMessageBox.warning(self, self.lang["warning"], self.lang["missing_info"])
            return None
        return {
            "name": name,
            "theme": {
                "primary": self.primary_color.name(),
                "secondary": self.secondary_color.name(),
                "background": self.background_color.name(),
                "text_dark": self.text_dark_color.name(),
                "text_light": self.text_light_color.name(),
                "danger": self.danger_color.name(),
                "warning": self.warning_color.name(),
            }
        }
class AppThemeManager:
    """Manages theme operations for the application."""
    def __init__(self, app):
        self.app = app
    def generate_stylesheet_from_theme(self) -> str:
        """
        Dynamically generates the QSS stylesheet from a theme, calculating derived colors
        and ensuring a more consistent look by avoiding pure white backgrounds.
        """
        theme_name = self.app.settings_manager.get_setting("theme_name", "Green Harmony")
        theme_data = self.app.all_themes.get(theme_name, APP_THEMES["Green Harmony"])
        colors = theme_data.copy()
        def adjust_color(hex_color, factor):
            try:
                color = QColor(hex_color)
                return color.lighter(int(factor)) if factor > 100 else color.darker(int(factor))
            except Exception:
                return hex_color
        bg_qcolor = QColor(colors['background'])
        if 'background_alt' not in colors:
            colors['background_alt'] = bg_qcolor.lighter(103).name() if bg_qcolor.lightness() < 230 else bg_qcolor.darker(103).name()
        if 'tertiary' not in colors:
            colors['tertiary'] = adjust_color(QColor(colors['secondary']), 120).name()
        if 'border' not in colors:
            colors['border'] = adjust_color(QColor(colors['background']), 90).name()
        return f"""
            QMainWindow, QDialog, QWidget {{
                background-color: {colors['background']};
                color: {colors['text_dark']};
            }}
            QGroupBox {{
                font-weight: bold;
                border: 1px solid {colors['secondary']};
                border-radius: 6px;
                margin-top: 12px;
            }}
            QGroupBox::title {{
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                background-color: {colors['background']};
                color: {colors['primary']};
            }}
            QLabel {{
                background-color: transparent;
            }}
            QLineEdit, QTextEdit, QComboBox, QDateEdit, QSpinBox {{
                border: 1px solid {colors['border']};
                padding: 5px;
                border-radius: 4px;
                background-color: {colors['background_alt']};
            }}
            QLineEdit:focus, QTextEdit:focus, QComboBox:focus, QDateEdit:focus {{
                border: 2px solid {colors['secondary']};
            }}
            QPushButton {{
                background-color: {colors['secondary']};
                color: {colors['text_light']};
                font-weight: bold; border: none;
                padding: 8px 16px;
                border-radius: 4px;
            }}
            QPushButton:hover {{
                background-color: {colors['tertiary']};
                color: {'#000000' if QColor(colors['tertiary']).lightness() > 128 else '#FFFFFF'};
            }}
            QPushButton:pressed {{
                background-color: {colors['primary']};
            }}
            QPushButton:disabled {{
                background-color: #CCCCCC;
                color: #888888;
                border: 1px solid #BBBBBB;
            }}
            QPushButton#dangerButton {{
                background-color: {colors['danger']};
                color: {colors['text_light']};
            }}
            QPushButton#dangerButton:hover {{
                background-color: {adjust_color(QColor(colors['danger']), 120).name()};
            }}
            QPushButton#primaryButton {{
                background-color: {colors['primary']};
            }}
            QPushButton#primaryButton:hover {{
                background-color: {colors['tertiary']};
                color: {'#000000' if QColor(colors['tertiary']).lightness() > 128 else '#FFFFFF'};
            }}
            QToolBar {{
                background-color: {colors['background_alt']};
                border-bottom: 1px solid {colors['border']};
            }}
            QTabWidget::pane {{
                border: 1px solid {colors['border']};
                border-top: none;
                background-color: {colors['background_alt']};
            }}
            QTabBar::tab {{
                background: {colors['secondary']};
                color: {colors['text_light']};
                padding: 6px 12px;
                border: 1px solid {colors['border']};
                border-bottom: none;
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                font-size: 11px;
            }}
            QTabBar::tab:hover {{
                background: {colors['tertiary']};
                color: {'#000000' if QColor(colors['tertiary']).lightness() > 128 else '#FFFFFF'};
            }}
            QTabBar::tab:selected {{
                background: {colors['primary']};
                color: {colors['text_light']};
                font-weight: bold;
            }}
            QTableWidget, QListWidget {{
                border: 1px solid {colors['border']};
                gridline-color: {colors['border']};
                background-color: {colors['background_alt']};
                alternate-background-color: {colors['background']};
            }}
            QHeaderView::section {{
                background-color: {colors['primary']};
                color: {colors['text_light']};
                padding: 5px;
                border: 1px solid {colors['primary']};
                font-weight: bold;
                text-align: center;
            }}
            QTableWidget::item, QListWidget::item {{
                padding: 3px;
            }}
            QTableWidget::item:selected, QListWidget::item:selected {{
                background-color: {colors['tertiary']};
                color: {'#000000' if QColor(colors['tertiary']).lightness() > 128 else '#FFFFFF'};
            }}
            QStatusBar {{
                background-color: {colors['secondary']};
                color: {colors['text_light']};
                font-weight: bold;
            }}
            QComboBox QAbstractItemView {{
                border: 1px solid {colors['border']};
                background-color: {colors['background_alt']};
                selection-background-color: {colors['tertiary']};
                color: {colors['text_dark']};
            }}
            QCheckBox::indicator {{
                width: 15px;
                height: 15px;
                border: 1px solid {colors['secondary']};
                border-radius: 3px;
            }}
            QCheckBox::indicator:unchecked {{
                background-color: {colors['background_alt']};
            }}
            QCheckBox::indicator:checked {{
                background-color: {colors['secondary']};
                image: url({(RESOURCES_DIR / 'check.png').as_posix()});
            }}
            QRadioButton::indicator {{
                width: 15px;
                height: 15px;
                border: 1px solid {colors['secondary']};
                border-radius: 8px;
            }}
            QRadioButton::indicator:checked {{
                background-color: {colors['secondary']};
            }}
            QToolButton {{
                background-color: {colors['secondary']};
                color: {colors['text_light']};
                border: 1px solid {colors['border']};
                border-radius: 8px;
                font-weight: bold;
                font-size: 13px;
            }}
            QToolButton:hover {{
                background-color: {colors['tertiary']};
                border: 2px solid {colors['primary']};
                color: #FFFFFF;
            }}
            QToolButton:pressed {{
                background-color: {colors['primary']};
                color: #000000;
            }}
            /* Calendar Widget Styling */
            QCalendarWidget QWidget#qt_calendar_navigationbar {{ background-color: {colors['primary']}; }}
            QCalendarWidget QToolButton {{ color: {colors['text_light']}; background-color: {colors['secondary']}; font-weight: bold; }}
            QCalendarWidget QToolButton:hover {{ background-color: {colors['tertiary']}; }}
            QCalendarWidget QMenu {{ background-color: {colors['background_alt']}; color: {colors['text_dark']}; }}
            QCalendarWidget QTableView {{ background-color: {colors['background_alt']}; alternate-background-color: {colors['background']}; }}
            QCalendarWidget QTableView::item:selected {{ background-color: {colors['secondary']}; color: {colors['text_light']}; }}
            QCalendarWidget #qt_calendar_weekday-cell {{ background-color: {colors['background_alt']}; color: {colors['primary']}; font-weight: bold; }}
            QCalendarWidget #qt_calendar_monthbutton, QCalendarWidget #qt_calendar_yearbutton {{ color: {colors['text_light']}; font-weight: bold; }}
        """
    def apply_theme(self):
        """Applies the current theme to the application."""
        stylesheet = self.generate_stylesheet_from_theme()
        self.app.setStyleSheet(stylesheet)
        QApplication.instance().setStyleSheet(stylesheet)




