"""File model view component."""

from __future__ import annotations

from typing import TYPE_CHECKING

from PySide2.QtWidgets import (
    QComboBox,
    QFormLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QSpinBox,
    QTextEdit,
    QVBoxLayout,
    QWidget,
)

if TYPE_CHECKING:
    from pytola_sim.lscsim.core.main_controller import MainController


class FileModelView(QWidget):
    """File model view component."""

    def __init__(self, controller: MainController) -> None:
        super().__init__()
        self.controller = controller
        self._setup_ui()

    def _setup_ui(self) -> None:
        main_layout = QVBoxLayout(self)

        # Project section
        project_group = QGroupBox("项目管理")
        project_layout = QVBoxLayout(project_group)

        # Project buttons
        project_buttons_layout = QHBoxLayout()
        self.new_project_btn = QPushButton("新建项目")
        self.open_project_btn = QPushButton("打开项目")
        self.save_project_btn = QPushButton("保存项目")

        project_buttons_layout.addWidget(self.new_project_btn)
        project_buttons_layout.addWidget(self.open_project_btn)
        project_buttons_layout.addWidget(self.save_project_btn)
        project_buttons_layout.addStretch()

        project_layout.addLayout(project_buttons_layout)

        # Project info form
        form_layout = QFormLayout()
        self.project_name_edit = QLineEdit()
        self.project_desc_edit = QTextEdit()
        self.project_desc_edit.setMaximumHeight(60)

        form_layout.addRow("项目名称:", self.project_name_edit)
        form_layout.addRow("项目描述:", self.project_desc_edit)

        project_layout.addLayout(form_layout)
        main_layout.addWidget(project_group)

        # Modeling preparation section
        prep_group = QGroupBox("建模准备")
        prep_layout = QVBoxLayout(prep_group)

        # Coordinate import
        coord_layout = QHBoxLayout()
        self.coord_file_edit = QLineEdit()
        self.browse_coord_btn = QPushButton("浏览")
        self.import_coord_btn = QPushButton("导入坐标")

        coord_layout.addWidget(QLabel("坐标文件:"))
        coord_layout.addWidget(self.coord_file_edit)
        coord_layout.addWidget(self.browse_coord_btn)
        coord_layout.addWidget(self.import_coord_btn)

        prep_layout.addLayout(coord_layout)

        # Target plate selection
        target_layout = QHBoxLayout()
        self.target_combo = QComboBox()
        self.target_combo.addItems(["标准装甲板", "复合装甲", "民用钢板"])
        self.select_target_btn = QPushButton("选择靶板")

        target_layout.addWidget(QLabel("靶板结构:"))
        target_layout.addWidget(self.target_combo)
        target_layout.addWidget(self.select_target_btn)

        prep_layout.addLayout(target_layout)

        # Material selection
        material_layout = QHBoxLayout()
        self.material_combo = QComboBox()
        self.material_combo.addItems(["结构钢", "铝合金", "钛合金"])
        self.select_material_btn = QPushButton("选择材料")

        material_layout.addWidget(QLabel("材料选择:"))
        material_layout.addWidget(self.material_combo)
        material_layout.addWidget(self.select_material_btn)

        prep_layout.addLayout(material_layout)

        # Explosion parameters
        param_layout = QHBoxLayout()
        self.height_spin = QSpinBox()
        self.height_spin.setRange(0, 1000)
        self.height_spin.setValue(100)

        self.det_x_edit = QLineEdit("0.0")
        self.det_y_edit = QLineEdit("0.0")
        self.det_z_edit = QLineEdit("0.0")

        param_layout.addWidget(QLabel("炸高(mm):"))
        param_layout.addWidget(self.height_spin)
        param_layout.addWidget(QLabel("起爆点(X,Y,Z):"))
        param_layout.addWidget(self.det_x_edit)
        param_layout.addWidget(self.det_y_edit)
        param_layout.addWidget(self.det_z_edit)

        prep_layout.addLayout(param_layout)

        # Template selection
        template_layout = QHBoxLayout()
        self.template_combo = QComboBox()
        self.template_combo.addItems(["静态分析模板", "动态冲击模板", "热分析模板"])
        self.apply_template_btn = QPushButton("应用模板")

        template_layout.addWidget(QLabel("分析模板:"))
        template_layout.addWidget(self.template_combo)
        template_layout.addWidget(self.apply_template_btn)

        prep_layout.addLayout(template_layout)

        main_layout.addWidget(prep_group)
        main_layout.addStretch()

        # Connect signals
        self._connect_signals()

    def _connect_signals(self) -> None:
        """Connect UI signals to slots."""
        self.new_project_btn.clicked.connect(self._on_new_project)
        self.open_project_btn.clicked.connect(self._on_open_project)
        self.save_project_btn.clicked.connect(self._on_save_project)
        self.browse_coord_btn.clicked.connect(self._on_browse_coordinates)
        self.import_coord_btn.clicked.connect(self._on_import_coordinates)
        self.select_target_btn.clicked.connect(self._on_select_target)
        self.select_material_btn.clicked.connect(self._on_select_material)
        self.apply_template_btn.clicked.connect(self._on_apply_template)

    def _on_new_project(self) -> None:
        """Handle new project button click."""
        project_name = self.project_name_edit.text()
        project_desc = self.project_desc_edit.toPlainText()
        if project_name:
            # Send command to controller
            self.controller.execute_command(
                "File.NewProject",
                {"name": project_name, "description": project_desc},
            )

    def _on_open_project(self) -> None:
        """Handle open project button click."""
        # Send command to controller
        self.controller.execute_command("File.OpenProject")

    def _on_save_project(self) -> None:
        """Handle save project button click."""
        # Send command to controller
        self.controller.execute_command("File.SaveProject")

    def _on_browse_coordinates(self) -> None:
        """Handle browse coordinates button click."""
        from PySide2.QtWidgets import QFileDialog

        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择坐标文件",
            "",
            "文本文件 (*.txt *.csv);;所有文件 (*)",
        )
        if file_path:
            self.coord_file_edit.setText(file_path)

    def _on_import_coordinates(self) -> None:
        """Handle import coordinates button click."""
        file_path = self.coord_file_edit.text()
        if file_path:
            self.controller.execute_command(
                "File.ImportCoordinates",
                {"file_path": file_path},
            )

    def _on_select_target(self) -> None:
        """Handle select target button click."""
        target_type = self.target_combo.currentText()
        self.controller.execute_command(
            "File.SelectTargetPlate",
            {"plate_type": target_type},
        )

    def _on_select_material(self) -> None:
        """Handle select material button click."""
        material_name = self.material_combo.currentText()
        self.controller.execute_command(
            "File.SelectMaterial",
            {"material_name": material_name},
        )

    def _on_apply_template(self) -> None:
        """Handle apply template button click."""
        template_name = self.template_combo.currentText()
        explosion_height = self.height_spin.value()
        detonation_point = [
            float(self.det_x_edit.text()),
            float(self.det_y_edit.text()),
            float(self.det_z_edit.text()),
        ]

        self.controller.execute_command(
            "File.SelectTemplate",
            {
                "template_name": template_name,
                "explosion_height": explosion_height,
                "detonation_point": detonation_point,
            },
        )
