"""
Element operations mixin for pyPhotoAlbum
"""

from PyQt6.QtWidgets import QFileDialog
from pyPhotoAlbum.decorators import ribbon_action
from pyPhotoAlbum.models import ImageData, TextBoxData, PlaceholderData
from pyPhotoAlbum.commands import AddElementCommand
from pyPhotoAlbum.async_backend import get_image_dimensions


class ElementOperationsMixin:
    """Mixin providing element creation and manipulation operations"""

    @ribbon_action(
        label="Image", tooltip="Add an image to the current page", tab="Insert", group="Media", requires_page=True
    )
    def add_image(self):
        """Add an image to the current page"""
        if not self.require_page():
            return

        file_path, _ = QFileDialog.getOpenFileName(
            self, "Select Image", "", "Image Files (*.jpg *.jpeg *.png *.gif *.bmp *.tiff *.webp);;All Files (*)"
        )

        if not file_path:
            return

        current_page = self.get_current_page()
        if not current_page:
            return

        try:
            # Import asset to project
            asset_path = self.project.asset_manager.import_asset(file_path)

            # Get dimensions using centralized utility (max 300px for UI display)
            full_asset_path = self.get_asset_full_path(asset_path)
            dimensions = get_image_dimensions(full_asset_path, max_size=300)
            if dimensions:
                img_width, img_height = dimensions
            else:
                # Fallback dimensions if image cannot be read
                img_width, img_height = 200, 150

            # Create image element at center of page
            page_width_mm = current_page.layout.size[0]
            page_height_mm = current_page.layout.size[1]

            # Center position
            x = (page_width_mm - img_width) / 2
            y = (page_height_mm - img_height) / 2

            new_image = ImageData(image_path=asset_path, x=x, y=y, width=img_width, height=img_height)

            # Add element using command pattern for undo/redo
            cmd = AddElementCommand(current_page.layout, new_image, asset_manager=self.project.asset_manager)
            self.project.history.execute(cmd)

            self.update_view()
            self.show_status("Added image (Ctrl+Z to undo)", 2000)
            print(f"Added image to page {self.get_current_page_index() + 1}: {asset_path}")

        except Exception as e:
            self.show_error("Error", f"Failed to add image: {str(e)}")
            print(f"Error adding image: {e}")

    @ribbon_action(
        label="Text", tooltip="Add a text box to the current page", tab="Insert", group="Media", requires_page=True
    )
    def add_text(self):
        """Add text to the current page"""
        if not self.require_page():
            return

        current_page = self.get_current_page()
        if not current_page:
            return

        # Create text box element at center of page
        page_width_mm = current_page.layout.size[0]
        page_height_mm = current_page.layout.size[1]

        text_width = 200
        text_height = 50

        # Center position
        x = (page_width_mm - text_width) / 2
        y = (page_height_mm - text_height) / 2

        new_text = TextBoxData(text_content="New Text", x=x, y=y, width=text_width, height=text_height)

        current_page.layout.add_element(new_text)
        self.update_view()

        print(f"Added text box to page {self.get_current_page_index() + 1}")

    @ribbon_action(
        label="Placeholder",
        tooltip="Add a placeholder to the current page",
        tab="Insert",
        group="Media",
        requires_page=True,
    )
    def add_placeholder(self):
        """Add a placeholder to the current page"""
        if not self.require_page():
            return

        current_page = self.get_current_page()
        if not current_page:
            return

        # Create placeholder element at center of page
        page_width_mm = current_page.layout.size[0]
        page_height_mm = current_page.layout.size[1]

        placeholder_width = 200
        placeholder_height = 150

        # Center position
        x = (page_width_mm - placeholder_width) / 2
        y = (page_height_mm - placeholder_height) / 2

        new_placeholder = PlaceholderData(
            placeholder_type="image", x=x, y=y, width=placeholder_width, height=placeholder_height
        )

        current_page.layout.add_element(new_placeholder)
        self.update_view()

        print(f"Added placeholder to page {self.get_current_page_index() + 1}")
