"""Create Workspace dialogs for advanced and guided flows."""

from ..qt_compat import QDialog, QComboBox, QLabel, exec_dialog
from typing import List, Optional
import uuid

from .base_dialog import BaseDialog
from .widgets import LayerSelectorWidget
from ..comment_formats import apply_sidecar
from ..models import Project, Assessment
from ..translator import tr, add_listener, remove_listener


class CreateProjectDialog(BaseDialog):
    """
    Dialog for creating only a new EMDS Workspace.

    Advanced users create Study Areas explicitly after the Workspace exists.
    The guided quick-start uses CreateGuidedProjectDialog below.
    """

    def __init__(self, available_layers: List[str] = None, parent=None):
        super().__init__(tr("create_workspace.window_title"), parent, width=600, height=520)
        self.available_layers = available_layers or []
        self.init_ui()
        self.retranslateUi()
        add_listener(self.retranslateUi)

    def init_ui(self):
        """Initialize dialog UI"""
        layout = self.create_main_layout()

        self.hint_panel = self.add_hint_panel(
            layout,
            tr("create_workspace.hint_title"),
            tr("create_workspace.hint_body"),
            link_key="create_workspace",
        )

        self.name_input = self.add_text_field(layout, tr("create_workspace.lbl_name"))

        self.description_input = self.add_rich_text_field(
            layout, tr("create_workspace.lbl_description")
        )

        self.layers_label = QLabel(tr("create_workspace.lbl_layers"))
        layout.addWidget(self.layers_label)
        self.layer_selector = LayerSelectorWidget(self.available_layers, self)
        layout.addWidget(self.layer_selector)

        self.add_buttons(layout)

    def retranslateUi(self):
        """Re-apply translated text to every translatable widget."""
        self.setWindowTitle(tr("create_workspace.window_title"))
        if hasattr(self, "hint_panel"):
            self.hint_panel.title_label.setText(tr("create_workspace.hint_title"))
            self.hint_panel.body_label.setText(tr("create_workspace.hint_body"))
            link_label = getattr(self.hint_panel, "link_label", None)
            if link_label is not None and hasattr(link_label, "retranslate"):
                link_label.retranslate()
        if hasattr(self, "name_input"):
            self.name_input._field_label.setText(tr("create_workspace.lbl_name"))
        if hasattr(self, "description_input"):
            self.description_input._field_label.setText(tr("create_workspace.lbl_description"))
        if hasattr(self, "layers_label"):
            self.layers_label.setText(tr("create_workspace.lbl_layers"))

    def closeEvent(self, event):
        remove_listener(self.retranslateUi)
        super().closeEvent(event)

    def get_project(self) -> Optional[Project]:
        if exec_dialog(self) == QDialog.DialogCode.Accepted:
            if not self.validate_required_field(self.name_input, tr("create_workspace.validation_name")):
                return self.get_project()

            project = Project(
                id=str(uuid.uuid4()),
                name=self.name_input.text().strip(),
                description=self.description_input.plain_text(),
            )
            project.metadata = apply_sidecar(
                {
                    "input_layers": self.layer_selector.get_selected_layers(),
                    "layer_count": len(self.layer_selector.get_selected_layers()),
                },
                self.description_input.html(),
            )
            return project

        return None


class CreateGuidedProjectDialog(BaseDialog):
    """
    Guided quick-start dialog for creating a Workspace and first Study Area.
    """

    def __init__(self, available_layers: List[str] = None, parent=None):
        super().__init__(tr("create_workspace_guided.window_title"), parent, width=600, height=620)
        self.available_layers = available_layers or []
        self.init_ui()
        self.retranslateUi()
        add_listener(self.retranslateUi)

    def init_ui(self):
        """Initialize dialog UI"""
        layout = self.create_main_layout()

        self.hint_panel = self.add_hint_panel(
            layout,
            tr("create_workspace_guided.hint_title"),
            tr("create_workspace_guided.hint_body"),
            link_key="create_workspace",
        )

        self.name_input = self.add_text_field(layout, tr("create_workspace.lbl_name"))

        self.description_input = self.add_rich_text_field(
            layout, tr("create_workspace.lbl_description")
        )

        self.study_name_input = self.add_text_field(layout, tr("create_workspace_guided.lbl_study_name"))

        self.target_layer_label = QLabel(tr("create_workspace_guided.lbl_target_layer"))
        layout.addWidget(self.target_layer_label)
        self.target_layer_combo = QComboBox(self)
        self.target_layer_combo.addItems(self.available_layers)
        layout.addWidget(self.target_layer_combo)

        self.overlay_layers_label = QLabel(tr("create_workspace_guided.lbl_overlay_layers"))
        layout.addWidget(self.overlay_layers_label)
        self.layer_selector = LayerSelectorWidget(self.available_layers, self)
        layout.addWidget(self.layer_selector)

        # Buttons
        self.add_buttons(layout)

    def retranslateUi(self):
        self.setWindowTitle(tr("create_workspace_guided.window_title"))
        if hasattr(self, "hint_panel"):
            self.hint_panel.title_label.setText(tr("create_workspace_guided.hint_title"))
            self.hint_panel.body_label.setText(tr("create_workspace_guided.hint_body"))
            link_label = getattr(self.hint_panel, "link_label", None)
            if link_label is not None and hasattr(link_label, "retranslate"):
                link_label.retranslate()
        if hasattr(self, "name_input"):
            self.name_input._field_label.setText(tr("create_workspace.lbl_name"))
        if hasattr(self, "description_input"):
            self.description_input._field_label.setText(tr("create_workspace.lbl_description"))
        if hasattr(self, "study_name_input"):
            self.study_name_input._field_label.setText(tr("create_workspace_guided.lbl_study_name"))
        if hasattr(self, "target_layer_label"):
            self.target_layer_label.setText(tr("create_workspace_guided.lbl_target_layer"))
        if hasattr(self, "overlay_layers_label"):
            self.overlay_layers_label.setText(tr("create_workspace_guided.lbl_overlay_layers"))

    def closeEvent(self, event):
        remove_listener(self.retranslateUi)
        super().closeEvent(event)

    def get_project(self) -> Optional[Project]:
        """Show dialog and return created project or None if cancelled."""
        if exec_dialog(self) == QDialog.DialogCode.Accepted:
            # Validate project name
            if not self.validate_required_field(self.name_input, tr("create_workspace.validation_name")):
                return self.get_project()  # Re-show dialog
            if not self.validate_required_field(self.study_name_input, tr("create_workspace_guided.validation_study_name")):
                return self.get_project()  # Re-show dialog

            target_layer = self.target_layer_combo.currentText().strip()
            overlay_layers = self.layer_selector.get_selected_layers()
            selected_layers = []
            if target_layer:
                selected_layers.append(target_layer)
            selected_layers.extend(layer for layer in overlay_layers if layer != target_layer)
            if not target_layer:
                self.show_warning(
                    tr("create_workspace_guided.warning_no_target_title"),
                    tr("create_workspace_guided.warning_no_target_body"),
                )
                return self.get_project()  # Re-show dialog

            project = Project(
                id=str(uuid.uuid4()),
                name=self.name_input.text().strip(),
                description=self.description_input.plain_text(),
            )

            project.metadata = apply_sidecar(
                {
                    'input_layers': selected_layers,
                    'target_layer_name': target_layer,
                    'overlay_layer_names': [layer for layer in selected_layers if layer != target_layer],
                    'layer_count': len(selected_layers),
                    'quickstart_study_name': self.study_name_input.text().strip(),
                },
                self.description_input.html(),
            )

            return project

        return None

    def get_quickstart_study(self, database_path: str = "") -> Optional[Assessment]:
        """Return the first Study Area requested by the quick-start dialog."""
        target_layer = self.target_layer_combo.currentText().strip()
        selected_layers = self.layer_selector.get_selected_layers()
        input_layers = [target_layer] + [layer for layer in selected_layers if layer != target_layer]
        study = Assessment(
            id=str(uuid.uuid4()),
            name=self.study_name_input.text().strip(),
            description="",
            input_layers=input_layers,
        )
        study.metadata = {
            "target_layer_name": target_layer,
            "study_layer_names": [layer for layer in input_layers if layer != target_layer],
            "assessment_layer_names": [layer for layer in input_layers if layer != target_layer],
            "overlay_layer_names": [layer for layer in input_layers if layer != target_layer],
            "input_layers": input_layers,
            "database_path": database_path,
            "selected_feature_count": 0,
        }
        return study
