"""Database views component."""

from __future__ import annotations

from typing import TYPE_CHECKING

from PySide2.QtWidgets import (
    QFormLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QSplitter,
    QTableWidget,
    QTableWidgetItem,
    QTabWidget,
    QTextEdit,
    QVBoxLayout,
    QWidget,
)

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


class DatabaseViews(QWidget):
    """Database views component."""

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

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

        # Create tab widget for different database types
        self.tab_widget = QTabWidget()

        # Product database tab
        self.product_tab = self._create_product_database_tab()
        self.tab_widget.addTab(self.product_tab, "产品数据库")

        # Simulation database tab
        self.simulation_tab = self._create_simulation_database_tab()
        self.tab_widget.addTab(self.simulation_tab, "仿真数据库")

        main_layout.addWidget(self.tab_widget)

        # Connect signals
        self._connect_signals()

    def _create_product_database_tab(self) -> QWidget:
        """Create product database tab."""
        widget = QWidget()
        layout = QHBoxLayout(widget)

        # Left panel - Product tree and search
        left_panel = QVBoxLayout()

        # Search section
        search_group = QGroupBox("搜索产品")
        search_layout = QHBoxLayout(search_group)

        self.product_search_edit = QLineEdit()
        self.product_search_edit.setPlaceholderText("输入产品名称或编号...")
        self.search_product_btn = QPushButton("搜索")

        search_layout.addWidget(self.product_search_edit)
        search_layout.addWidget(self.search_product_btn)

        left_panel.addWidget(search_group)

        # Product tree
        tree_group = QGroupBox("产品结构")
        tree_layout = QVBoxLayout(tree_group)

        self.product_tree = QTextEdit()
        self.product_tree.setMaximumWidth(300)
        self.product_tree.setPlaceholderText("产品树结构...")
        self.product_tree.setText(
            "产品库\n"
            "├── 防护装备\n"
            "│   ├── 防护装甲板\n"
            "│   └── 防弹衣\n"
            "├── 建筑防护\n"
            "│   └── 防爆门窗\n"
            "└── 测试设备\n"
            "    └── 冲击试验台",
        )

        tree_layout.addWidget(self.product_tree)

        left_panel.addWidget(tree_group)

        # Right panel - Product details
        right_panel = QVBoxLayout()

        # Product details
        details_group = QGroupBox("产品详情")
        details_layout = QVBoxLayout(details_group)

        # Product info form
        form_layout = QFormLayout()
        self.product_name_label = QLabel("--")
        self.product_code_label = QLabel("--")
        self.product_category_label = QLabel("--")
        self.product_desc_edit = QTextEdit()
        self.product_desc_edit.setMaximumHeight(80)
        self.product_desc_edit.setPlaceholderText("产品描述...")

        form_layout.addRow("产品名称:", self.product_name_label)
        form_layout.addRow("产品编号:", self.product_code_label)
        form_layout.addRow("产品类别:", self.product_category_label)
        form_layout.addRow("产品描述:", self.product_desc_edit)

        details_layout.addLayout(form_layout)

        # Action buttons
        action_layout = QHBoxLayout()
        self.add_product_btn = QPushButton("添加产品")
        self.edit_product_btn = QPushButton("编辑产品")
        self.delete_product_btn = QPushButton("删除产品")

        action_layout.addWidget(self.add_product_btn)
        action_layout.addWidget(self.edit_product_btn)
        action_layout.addWidget(self.delete_product_btn)

        details_layout.addLayout(action_layout)

        right_panel.addWidget(details_group)

        # Add panels to splitter
        splitter = QSplitter()
        left_widget = QWidget()
        left_widget.setLayout(left_panel)
        right_widget = QWidget()
        right_widget.setLayout(right_panel)

        splitter.addWidget(left_widget)
        splitter.addWidget(right_widget)
        splitter.setSizes([300, 500])

        layout.addWidget(splitter)

        return widget

    def _create_simulation_database_tab(self) -> QWidget:
        """Create simulation database tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Create sub-tabs for different simulation data types
        self.sim_tab_widget = QTabWidget()

        # Materials tab
        self.materials_tab = self._create_materials_tab()
        self.sim_tab_widget.addTab(self.materials_tab, "材料库")

        # Target plates tab
        self.target_plates_tab = self._create_target_plates_tab()
        self.sim_tab_widget.addTab(self.target_plates_tab, "靶板结构")

        # Templates tab
        self.templates_tab = self._create_templates_tab()
        self.sim_tab_widget.addTab(self.templates_tab, "分析模板")

        layout.addWidget(self.sim_tab_widget)

        return widget

    def _create_materials_tab(self) -> QWidget:
        """Create materials database tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Search section
        search_layout = QHBoxLayout()
        self.material_search_edit = QLineEdit()
        self.material_search_edit.setPlaceholderText("搜索材料...")
        self.search_material_btn = QPushButton("搜索")
        self.add_material_btn = QPushButton("添加材料")

        search_layout.addWidget(QLabel("材料搜索:"))
        search_layout.addWidget(self.material_search_edit)
        search_layout.addWidget(self.search_material_btn)
        search_layout.addWidget(self.add_material_btn)

        layout.addLayout(search_layout)

        # Materials table
        self.materials_table = QTableWidget()
        self.materials_table.setColumnCount(6)
        self.materials_table.setHorizontalHeaderLabels(
            [
                "材料名称",
                "密度",
                "弹性模量",
                "泊松比",
                "屈服强度",
                "类别",
            ],
        )

        # Sample data
        sample_materials = [
            ["结构钢", "7850 kg/m³", "200 GPa", "0.3", "250 MPa", "金属材料"],
            ["铝合金", "2700 kg/m³", "70 GPa", "0.33", "276 MPa", "金属材料"],
            ["钛合金", "4430 kg/m³", "114 GPa", "0.34", "880 MPa", "金属材料"],
            ["混凝土", "2400 kg/m³", "30 GPa", "0.2", "20 MPa", "建筑材料"],
        ]

        self.materials_table.setRowCount(len(sample_materials))
        for row, material_data in enumerate(sample_materials):
            for col, data in enumerate(material_data):
                self.materials_table.setItem(row, col, QTableWidgetItem(str(data)))

        self.materials_table.resizeColumnsToContents()
        layout.addWidget(self.materials_table)

        # Material details
        details_group = QGroupBox("材料属性详情")
        details_layout = QFormLayout(details_group)

        self.mat_density_label = QLabel("--")
        self.mat_young_label = QLabel("--")
        self.mat_poisson_label = QLabel("--")
        self.mat_yield_label = QLabel("--")

        details_layout.addRow("密度:", self.mat_density_label)
        details_layout.addRow("弹性模量:", self.mat_young_label)
        details_layout.addRow("泊松比:", self.mat_poisson_label)
        details_layout.addRow("屈服强度:", self.mat_yield_label)

        layout.addWidget(details_group)

        return widget

    def _create_target_plates_tab(self) -> QWidget:
        """Create target plates database tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Search and actions
        search_layout = QHBoxLayout()
        self.plate_search_edit = QLineEdit()
        self.plate_search_edit.setPlaceholderText("搜索靶板...")
        self.search_plate_btn = QPushButton("搜索")
        self.add_plate_btn = QPushButton("添加靶板")

        search_layout.addWidget(QLabel("靶板搜索:"))
        search_layout.addWidget(self.plate_search_edit)
        search_layout.addWidget(self.search_plate_btn)
        search_layout.addWidget(self.add_plate_btn)

        layout.addLayout(search_layout)

        # Target plates table
        self.plates_table = QTableWidget()
        self.plates_table.setColumnCount(5)
        self.plates_table.setHorizontalHeaderLabels(
            [
                "靶板名称",
                "类型",
                "厚度",
                "材料",
                "尺寸",
            ],
        )

        # Sample data
        sample_plates = [
            ["标准装甲板", "装甲防护", "20 mm", "结构钢", "1000x500 mm"],
            ["复合装甲", "装甲防护", "30 mm", "陶瓷+金属", "1200x600 mm"],
            ["民用钢板", "结构材料", "10 mm", "普通钢", "2000x1000 mm"],
        ]

        self.plates_table.setRowCount(len(sample_plates))
        for row, plate_data in enumerate(sample_plates):
            for col, data in enumerate(plate_data):
                self.plates_table.setItem(row, col, QTableWidgetItem(str(data)))

        self.plates_table.resizeColumnsToContents()
        layout.addWidget(self.plates_table)

        return widget

    def _create_templates_tab(self) -> QWidget:
        """Create templates database tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Search and actions
        search_layout = QHBoxLayout()
        self.template_search_edit = QLineEdit()
        self.template_search_edit.setPlaceholderText("搜索模板...")
        self.search_template_btn = QPushButton("搜索")
        self.add_template_btn = QPushButton("添加模板")

        search_layout.addWidget(QLabel("模板搜索:"))
        search_layout.addWidget(self.template_search_edit)
        search_layout.addWidget(self.search_template_btn)
        search_layout.addWidget(self.add_template_btn)

        layout.addLayout(search_layout)

        # Templates table
        self.templates_table = QTableWidget()
        self.templates_table.setColumnCount(4)
        self.templates_table.setHorizontalHeaderLabels(
            [
                "模板名称",
                "分析类型",
                "求解器",
                "描述",
            ],
        )

        # Sample data
        sample_templates = [
            ["静态结构分析", "静态分析", "隐式求解器", "标准静态结构分析模板"],
            ["冲击动力分析", "动态分析", "显式求解器", "显式动力冲击分析模板"],
            ["热传导分析", "热分析", "隐式求解器", "稳态热传导分析模板"],
        ]

        self.templates_table.setRowCount(len(sample_templates))
        for row, template_data in enumerate(sample_templates):
            for col, data in enumerate(template_data):
                self.templates_table.setItem(row, col, QTableWidgetItem(str(data)))

        self.templates_table.resizeColumnsToContents()
        layout.addWidget(self.templates_table)

        return widget

    def _connect_signals(self) -> None:
        """Connect UI signals to slots."""
        # Product database signals
        self.search_product_btn.clicked.connect(self._on_search_products)
        self.add_product_btn.clicked.connect(self._on_add_product)
        self.edit_product_btn.clicked.connect(self._on_edit_product)
        self.delete_product_btn.clicked.connect(self._on_delete_product)

        # Simulation database signals
        self.search_material_btn.clicked.connect(self._on_search_materials)
        self.add_material_btn.clicked.connect(self._on_add_material)
        self.search_plate_btn.clicked.connect(self._on_search_plates)
        self.add_plate_btn.clicked.connect(self._on_add_plate)
        self.search_template_btn.clicked.connect(self._on_search_templates)
        self.add_template_btn.clicked.connect(self._on_add_template)

        # Table selection signals
        self.materials_table.cellClicked.connect(self._on_material_selected)
        self.plates_table.cellClicked.connect(self._on_plate_selected)
        self.templates_table.cellClicked.connect(self._on_template_selected)

    def _on_search_products(self) -> None:
        """Handle product search."""
        search_term = self.product_search_edit.text()
        self.controller.execute_command(
            "ProductDB.SearchProducts",
            {"term": search_term},
        )

    def _on_add_product(self) -> None:
        """Handle add product."""
        self.controller.execute_command("ProductDB.AddProduct")

    def _on_edit_product(self) -> None:
        """Handle edit product."""
        self.controller.execute_command("ProductDB.UpdateProduct")

    def _on_delete_product(self) -> None:
        """Handle delete product."""
        self.controller.execute_command("ProductDB.DeleteProduct")

    def _on_search_materials(self) -> None:
        """Handle material search."""
        search_term = self.material_search_edit.text()
        self.controller.execute_command("SimDB.SearchMaterials", {"term": search_term})

    def _on_add_material(self) -> None:
        """Handle add material."""
        self.controller.execute_command("SimDB.AddMaterial")

    def _on_search_plates(self) -> None:
        """Handle target plate search."""
        search_term = self.plate_search_edit.text()
        self.controller.execute_command(
            "SimDB.SearchTargetPlates",
            {"term": search_term},
        )

    def _on_add_plate(self) -> None:
        """Handle add target plate."""
        self.controller.execute_command("SimDB.AddTargetPlate")

    def _on_search_templates(self) -> None:
        """Handle template search."""
        search_term = self.template_search_edit.text()
        self.controller.execute_command("SimDB.SearchTemplates", {"term": search_term})

    def _on_add_template(self) -> None:
        """Handle add template."""
        self.controller.execute_command("SimDB.AddTemplate")

    def _on_material_selected(self, row: int, column: int) -> None:
        """Handle material selection."""
        if row >= 0:
            self.materials_table.item(row, 0).text()
            # Update details display
            self.mat_density_label.setText(self.materials_table.item(row, 1).text())
            self.mat_young_label.setText(self.materials_table.item(row, 2).text())
            self.mat_poisson_label.setText(self.materials_table.item(row, 3).text())
            self.mat_yield_label.setText(self.materials_table.item(row, 4).text())

    def _on_plate_selected(self, row: int, column: int) -> None:
        """Handle plate selection."""
        if row >= 0:
            self.plates_table.item(row, 0).text()
            # Additional handling can be added here

    def _on_template_selected(self, row: int, column: int) -> None:
        """Handle template selection."""
        if row >= 0:
            self.templates_table.item(row, 0).text()
            # Additional handling can be added here
