"""
Style dialogs for pyPhotoAlbum

Dialogs for configuring image styling options:
- Corner radius
- Border (width and color)
- Drop shadow
"""

from typing import Tuple
from PyQt6.QtWidgets import (
    QDialog,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QSlider,
    QSpinBox,
    QDoubleSpinBox,
    QPushButton,
    QCheckBox,
    QColorDialog,
    QGroupBox,
    QFormLayout,
    QWidget,
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QColor


class CornerRadiusDialog(QDialog):
    """Dialog for setting corner radius"""

    def __init__(self, parent, current_radius: float = 0.0):
        super().__init__(parent)
        self.setWindowTitle("Corner Radius")
        self.setMinimumWidth(300)

        layout = QVBoxLayout(self)

        # Slider with label
        slider_layout = QHBoxLayout()
        slider_layout.addWidget(QLabel("Radius:"))

        self.slider = QSlider(Qt.Orientation.Horizontal)
        self.slider.setMinimum(0)
        self.slider.setMaximum(50)
        self.slider.setValue(int(current_radius))
        self.slider.valueChanged.connect(self._on_slider_changed)
        slider_layout.addWidget(self.slider)

        self.value_label = QLabel(f"{int(current_radius)}%")
        self.value_label.setMinimumWidth(40)
        slider_layout.addWidget(self.value_label)

        layout.addLayout(slider_layout)

        # Preset buttons
        preset_layout = QHBoxLayout()
        for value, label in [(0, "None"), (5, "Slight"), (15, "Medium"), (25, "Large"), (50, "Circle")]:
            btn = QPushButton(label)
            btn.clicked.connect(lambda checked, v=value: self.slider.setValue(v))
            preset_layout.addWidget(btn)
        layout.addLayout(preset_layout)

        # OK/Cancel buttons
        button_layout = QHBoxLayout()
        ok_btn = QPushButton("OK")
        ok_btn.clicked.connect(self.accept)
        cancel_btn = QPushButton("Cancel")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addStretch()
        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        layout.addLayout(button_layout)

    def _on_slider_changed(self, value):
        self.value_label.setText(f"{value}%")

    def get_value(self) -> float:
        return float(self.slider.value())


class ColorButton(QPushButton):
    """Button that shows a color and opens color picker on click"""

    def __init__(self, color: Tuple[int, int, int], parent=None):
        super().__init__(parent)
        self.setFixedSize(40, 25)
        self._color = color
        self._update_style()
        self.clicked.connect(self._pick_color)

    def _update_style(self):
        r, g, b = self._color
        self.setStyleSheet(f"background-color: rgb({r}, {g}, {b}); border: 1px solid #666;")

    def _pick_color(self):
        r, g, b = self._color
        initial = QColor(r, g, b)
        color = QColorDialog.getColor(initial, self, "Select Color")
        if color.isValid():
            self._color = (color.red(), color.green(), color.blue())
            self._update_style()

    def get_color(self) -> Tuple[int, int, int]:
        return self._color


class BorderDialog(QDialog):
    """Dialog for configuring border"""

    def __init__(
        self,
        parent,
        current_width: float = 0.0,
        current_color: Tuple[int, int, int] = (0, 0, 0),
    ):
        super().__init__(parent)
        self.setWindowTitle("Border Settings")
        self.setMinimumWidth(300)

        layout = QVBoxLayout(self)

        # Border width
        width_layout = QHBoxLayout()
        width_layout.addWidget(QLabel("Width (mm):"))
        self.width_spin = QDoubleSpinBox()
        self.width_spin.setRange(0, 20)
        self.width_spin.setSingleStep(0.5)
        self.width_spin.setValue(current_width)
        self.width_spin.setDecimals(1)
        width_layout.addWidget(self.width_spin)
        layout.addLayout(width_layout)

        # Border color
        color_layout = QHBoxLayout()
        color_layout.addWidget(QLabel("Color:"))
        self.color_btn = ColorButton(current_color)
        color_layout.addWidget(self.color_btn)
        color_layout.addStretch()
        layout.addLayout(color_layout)

        # Preset buttons
        preset_layout = QHBoxLayout()
        presets = [
            ("None", 0, (0, 0, 0)),
            ("Thin Black", 0.5, (0, 0, 0)),
            ("White", 2, (255, 255, 255)),
            ("Gold", 1.5, (212, 175, 55)),
        ]
        for label, width, color in presets:
            btn = QPushButton(label)
            btn.clicked.connect(lambda checked, w=width, c=color: self._apply_preset(w, c))
            preset_layout.addWidget(btn)
        layout.addLayout(preset_layout)

        # OK/Cancel buttons
        button_layout = QHBoxLayout()
        ok_btn = QPushButton("OK")
        ok_btn.clicked.connect(self.accept)
        cancel_btn = QPushButton("Cancel")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addStretch()
        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        layout.addLayout(button_layout)

    def _apply_preset(self, width, color):
        self.width_spin.setValue(width)
        self.color_btn._color = color
        self.color_btn._update_style()

    def get_values(self) -> Tuple[float, Tuple[int, int, int]]:
        return self.width_spin.value(), self.color_btn.get_color()


class ShadowDialog(QDialog):
    """Dialog for configuring drop shadow"""

    def __init__(
        self,
        parent,
        enabled: bool = False,
        offset: Tuple[float, float] = (2.0, 2.0),
        blur: float = 3.0,
        color: Tuple[int, int, int, int] = (0, 0, 0, 128),
    ):
        super().__init__(parent)
        self.setWindowTitle("Shadow Settings")
        self.setMinimumWidth(350)

        layout = QVBoxLayout(self)

        # Enable checkbox
        self.enabled_check = QCheckBox("Enable Drop Shadow")
        self.enabled_check.setChecked(enabled)
        self.enabled_check.stateChanged.connect(self._update_controls)
        layout.addWidget(self.enabled_check)

        # Settings group
        self.settings_group = QGroupBox("Shadow Settings")
        form = QFormLayout(self.settings_group)

        # Offset X
        self.offset_x = QDoubleSpinBox()
        self.offset_x.setRange(-20, 20)
        self.offset_x.setSingleStep(0.5)
        self.offset_x.setValue(offset[0])
        self.offset_x.setDecimals(1)
        form.addRow("Offset X (mm):", self.offset_x)

        # Offset Y
        self.offset_y = QDoubleSpinBox()
        self.offset_y.setRange(-20, 20)
        self.offset_y.setSingleStep(0.5)
        self.offset_y.setValue(offset[1])
        self.offset_y.setDecimals(1)
        form.addRow("Offset Y (mm):", self.offset_y)

        # Blur
        self.blur_spin = QDoubleSpinBox()
        self.blur_spin.setRange(0, 20)
        self.blur_spin.setSingleStep(0.5)
        self.blur_spin.setValue(blur)
        self.blur_spin.setDecimals(1)
        form.addRow("Blur (mm):", self.blur_spin)

        # Color
        color_widget = QWidget()
        color_layout = QHBoxLayout(color_widget)
        color_layout.setContentsMargins(0, 0, 0, 0)
        self.color_btn = ColorButton(color[:3])
        color_layout.addWidget(self.color_btn)
        color_layout.addStretch()
        form.addRow("Color:", color_widget)

        # Opacity
        self.opacity_slider = QSlider(Qt.Orientation.Horizontal)
        self.opacity_slider.setRange(0, 255)
        self.opacity_slider.setValue(color[3] if len(color) > 3 else 128)
        opacity_layout = QHBoxLayout()
        opacity_layout.addWidget(self.opacity_slider)
        self.opacity_label = QLabel(f"{self.opacity_slider.value()}")
        self.opacity_label.setMinimumWidth(30)
        opacity_layout.addWidget(self.opacity_label)
        self.opacity_slider.valueChanged.connect(lambda v: self.opacity_label.setText(str(v)))
        form.addRow("Opacity:", opacity_layout)

        layout.addWidget(self.settings_group)

        # Preset buttons
        preset_layout = QHBoxLayout()
        presets = [
            ("Subtle", True, (1.0, 1.0), 2.0, (0, 0, 0, 60)),
            ("Normal", True, (2.0, 2.0), 3.0, (0, 0, 0, 100)),
            ("Strong", True, (3.0, 3.0), 5.0, (0, 0, 0, 150)),
        ]
        for label, en, off, bl, col in presets:
            btn = QPushButton(label)
            btn.clicked.connect(lambda checked, e=en, o=off, b=bl, c=col: self._apply_preset(e, o, b, c))
            preset_layout.addWidget(btn)
        layout.addLayout(preset_layout)

        # OK/Cancel buttons
        button_layout = QHBoxLayout()
        ok_btn = QPushButton("OK")
        ok_btn.clicked.connect(self.accept)
        cancel_btn = QPushButton("Cancel")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addStretch()
        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        layout.addLayout(button_layout)

        self._update_controls()

    def _update_controls(self):
        self.settings_group.setEnabled(self.enabled_check.isChecked())

    def _apply_preset(self, enabled, offset, blur, color):
        self.enabled_check.setChecked(enabled)
        self.offset_x.setValue(offset[0])
        self.offset_y.setValue(offset[1])
        self.blur_spin.setValue(blur)
        self.color_btn._color = color[:3]
        self.color_btn._update_style()
        self.opacity_slider.setValue(color[3] if len(color) > 3 else 128)

    def get_values(self) -> Tuple[bool, Tuple[float, float], float, Tuple[int, int, int, int]]:
        color_rgb = self.color_btn.get_color()
        color_rgba = color_rgb + (self.opacity_slider.value(),)
        return (
            self.enabled_check.isChecked(),
            (self.offset_x.value(), self.offset_y.value()),
            self.blur_spin.value(),
            color_rgba,
        )
