#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
================================================================================
Модуль: Кубы в тонны
================================================================================
Пересчёт объёма сыпучих грузов в массу по плотности.
================================================================================
"""

from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
    QLineEdit, QPushButton, QGroupBox, QGridLayout,
    QDoubleSpinBox, QComboBox, QMessageBox, QScrollArea,
    QFrame, QTableWidget, QTableWidgetItem, QHeaderView,
    QApplication, QMainWindow
)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QColor, QBrush
from datetime import datetime


class CubesToTonsModule:
    """Класс модуля для ModuleManager"""
    
    display_name = "📦 Кубы в тонны"
    description = "Пересчёт сыпучих грузов: объём ↔ масса по плотности"
    
    def __init__(self, main_window):
        self.main_window = main_window
        self.widget = None
        self.window = None
    
    def run(self):
        """Запуск модуля — открывает интерфейс в отдельном окне"""
        self.widget = CubesToTonsWidget(self.main_window, self)
        
        self.window = QMainWindow()
        self.window.setWindowTitle(f"{self.display_name} - РейсМастер")
        self.window.setWindowIcon(self.main_window.windowIcon())
        self.window.setCentralWidget(self.widget)
        self.window.resize(1000, 700)
        self.window.show()


class CubesToTonsWidget(QWidget):
    """Интерфейс калькулятора Кубы в тонны"""
    
    MATERIALS = [
        ("Щебень гранитный (фр. 5-20)", 1.47),
        ("Щебень гранитный (фр. 20-40)", 1.38),
        ("Щебень гравийный", 1.45),
        ("Щебень известняковый", 1.30),
        ("Песок строительный (сухой)", 1.44),
        ("Песок речной (влажный)", 1.65),
        ("Песок карьерный", 1.50),
        ("Гравий", 1.60),
        ("Керамзит", 0.45),
        ("Цемент (насыпной)", 1.30),
        ("Цемент (в мешках)", 1.60),
        ("Земля/грунт (сухой)", 1.20),
        ("Земля/грунт (влажный)", 1.50),
        ("Торф", 0.40),
        ("Уголь каменный", 0.85),
        ("ПГС", 1.65),
        ("Отсев", 1.60),
        ("Асфальтовая крошка", 1.80),
        ("Другой", None)
    ]
    
    def __init__(self, main_window, module):
        super().__init__()
        self.main_window = main_window
        self.module = module
        self.history = []
        self.last_result = ""
        self.last_material = ""
        self.last_volume = 0
        self.last_mass = 0
        self.last_direction = ""
        self.setup_ui()
        self.connect_signals()
        self.update_from_material(0)
    
    def load_calculation(self, calculation: dict):
        """Загружает сохраненный расчет"""
        params = calculation.get('params', {})
        if not params:
            return
        
        material = params.get('material', '')
        density = params.get('density', 1.47)
        volume = params.get('volume', 0)
        mass = params.get('mass', 0)
        direction = params.get('direction', '')
        
        # Устанавливаем материал
        index = self.find_material_index(material)
        if index >= 0:
            self.material_combo.setCurrentIndex(index)
        
        self.density_spin.setValue(density)
        
        if "кубы → тонны" in direction or direction == "кубы → тонны":
            self.cubes_spin.setValue(volume)
            self.cubes_to_tons()
        else:
            self.tons_spin.setValue(mass)
            self.tons_to_cubes()
    
    def find_material_index(self, material_name):
        for i, (name, _) in enumerate(self.MATERIALS):
            if name == material_name:
                return i
        return 0
    
    def setup_ui(self):
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QFrame.NoFrame)
        
        scroll_content = QWidget()
        scroll_layout = QVBoxLayout(scroll_content)
        scroll_layout.setSpacing(15)
        scroll_layout.setContentsMargins(15, 15, 15, 15)
        
        header_layout = QHBoxLayout()
        title_label = QLabel("📦 КУБЫ В ТОННЫ")
        title_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #1a2a3a;")
        header_layout.addWidget(title_label)
        header_layout.addStretch()
        scroll_layout.addLayout(header_layout)
        
        calc_group = QGroupBox("📊 КАЛЬКУЛЯТОР")
        calc_group.setStyleSheet("""
            QGroupBox {
                font-size: 14px;
                font-weight: bold;
                border: 2px solid #c0c0c0;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 10px 0 10px;
            }
        """)
        
        calc_layout = QGridLayout(calc_group)
        calc_layout.setVerticalSpacing(12)
        calc_layout.setHorizontalSpacing(10)
        
        calc_layout.addWidget(QLabel("🧱 Материал:"), 0, 0)
        self.material_combo = QComboBox()
        for material, _ in self.MATERIALS:
            self.material_combo.addItem(material)
        self.material_combo.setMinimumHeight(32)
        calc_layout.addWidget(self.material_combo, 0, 1, 1, 2)
        
        calc_layout.addWidget(QLabel("⚖️ Плотность (т/м³):"), 1, 0)
        
        density_widget = QWidget()
        density_layout = QHBoxLayout(density_widget)
        density_layout.setContentsMargins(0, 0, 0, 0)
        density_layout.setSpacing(5)
        
        self.density_spin = QDoubleSpinBox()
        self.density_spin.setRange(0.01, 5.0)
        self.density_spin.setValue(1.47)
        self.density_spin.setDecimals(3)
        self.density_spin.setSingleStep(0.05)
        self.density_spin.setMinimumHeight(32)
        density_layout.addWidget(self.density_spin, 1)
        
        self.apply_density_btn = QPushButton("📋 Из справочника")
        self.apply_density_btn.setMinimumHeight(32)
        self.apply_density_btn.setMinimumWidth(140)
        self.apply_density_btn.clicked.connect(self.apply_density_from_combo)
        density_layout.addWidget(self.apply_density_btn)
        
        calc_layout.addWidget(density_widget, 1, 1, 1, 2)
        
        line1 = QFrame()
        line1.setFrameShape(QFrame.HLine)
        line1.setFrameShadow(QFrame.Sunken)
        calc_layout.addWidget(line1, 2, 0, 1, 3)
        
        calc_layout.addWidget(QLabel("📐 Объём (м³):"), 3, 0)
        
        cubes_widget = QWidget()
        cubes_layout = QHBoxLayout(cubes_widget)
        cubes_layout.setContentsMargins(0, 0, 0, 0)
        cubes_layout.setSpacing(10)
        
        self.cubes_spin = QDoubleSpinBox()
        self.cubes_spin.setRange(0, 10000)
        self.cubes_spin.setValue(10.0)
        self.cubes_spin.setDecimals(2)
        self.cubes_spin.setSingleStep(1.0)
        self.cubes_spin.setMinimumHeight(32)
        cubes_layout.addWidget(self.cubes_spin, 1)
        
        self.cubes_to_tons_btn = QPushButton("→ Пересчитать")
        self.cubes_to_tons_btn.setMinimumHeight(35)
        self.cubes_to_tons_btn.setMinimumWidth(130)
        self.cubes_to_tons_btn.setStyleSheet("""
            QPushButton {
                background-color: #1976D2;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 10pt;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1565C0;
            }
        """)
        self.cubes_to_tons_btn.clicked.connect(self.cubes_to_tons)
        cubes_layout.addWidget(self.cubes_to_tons_btn)
        
        calc_layout.addWidget(cubes_widget, 3, 1, 1, 2)
        
        calc_layout.addWidget(QLabel("⚖️ Масса (т):"), 4, 0)
        
        result_tons_widget = QWidget()
        result_tons_layout = QHBoxLayout(result_tons_widget)
        result_tons_layout.setContentsMargins(0, 0, 0, 0)
        result_tons_layout.setSpacing(5)
        
        self.tons_result = QLineEdit()
        self.tons_result.setReadOnly(True)
        self.tons_result.setMinimumHeight(35)
        self.tons_result.setStyleSheet("""
            QLineEdit {
                background-color: #e8f0fe;
                border: 1px solid #a0a0a0;
                border-radius: 4px;
                font-weight: bold;
                font-size: 12pt;
                padding: 3px;
            }
        """)
        result_tons_layout.addWidget(self.tons_result, 1)
        
        self.copy_tons_btn = QPushButton("📋 Копировать")
        self.copy_tons_btn.setMinimumHeight(32)
        self.copy_tons_btn.setMinimumWidth(100)
        self.copy_tons_btn.clicked.connect(lambda: self.copy_to_clipboard(self.tons_result.text()))
        result_tons_layout.addWidget(self.copy_tons_btn)
        
        calc_layout.addWidget(result_tons_widget, 4, 1, 1, 2)
        
        line2 = QFrame()
        line2.setFrameShape(QFrame.HLine)
        line2.setFrameShadow(QFrame.Sunken)
        calc_layout.addWidget(line2, 5, 0, 1, 3)
        
        calc_layout.addWidget(QLabel("⚖️ Масса (т):"), 6, 0)
        
        tons_widget = QWidget()
        tons_layout = QHBoxLayout(tons_widget)
        tons_layout.setContentsMargins(0, 0, 0, 0)
        tons_layout.setSpacing(10)
        
        self.tons_spin = QDoubleSpinBox()
        self.tons_spin.setRange(0, 10000)
        self.tons_spin.setValue(10.0)
        self.tons_spin.setDecimals(2)
        self.tons_spin.setSingleStep(1.0)
        self.tons_spin.setMinimumHeight(32)
        tons_layout.addWidget(self.tons_spin, 1)
        
        self.tons_to_cubes_btn = QPushButton("→ Пересчитать")
        self.tons_to_cubes_btn.setMinimumHeight(35)
        self.tons_to_cubes_btn.setMinimumWidth(130)
        self.tons_to_cubes_btn.setStyleSheet("""
            QPushButton {
                background-color: #1976D2;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 10pt;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1565C0;
            }
        """)
        self.tons_to_cubes_btn.clicked.connect(self.tons_to_cubes)
        tons_layout.addWidget(self.tons_to_cubes_btn)
        
        calc_layout.addWidget(tons_widget, 6, 1, 1, 2)
        
        calc_layout.addWidget(QLabel("📐 Объём (м³):"), 7, 0)
        
        result_cubes_widget = QWidget()
        result_cubes_layout = QHBoxLayout(result_cubes_widget)
        result_cubes_layout.setContentsMargins(0, 0, 0, 0)
        result_cubes_layout.setSpacing(5)
        
        self.cubes_result = QLineEdit()
        self.cubes_result.setReadOnly(True)
        self.cubes_result.setMinimumHeight(35)
        self.cubes_result.setStyleSheet("""
            QLineEdit {
                background-color: #e8f0fe;
                border: 1px solid #a0a0a0;
                border-radius: 4px;
                font-weight: bold;
                font-size: 12pt;
                padding: 3px;
            }
        """)
        result_cubes_layout.addWidget(self.cubes_result, 1)
        
        self.copy_cubes_btn = QPushButton("📋 Копировать")
        self.copy_cubes_btn.setMinimumHeight(32)
        self.copy_cubes_btn.setMinimumWidth(100)
        self.copy_cubes_btn.clicked.connect(lambda: self.copy_to_clipboard(self.cubes_result.text()))
        result_cubes_layout.addWidget(self.copy_cubes_btn)
        
        calc_layout.addWidget(result_cubes_widget, 7, 1, 1, 2)
        
        scroll_layout.addWidget(calc_group)
        
        fav_btn_layout = QHBoxLayout()
        fav_btn_layout.addStretch()
        
        self.fav_btn = QPushButton("⭐ В избранное")
        self.fav_btn.setMinimumHeight(40)
        self.fav_btn.setMinimumWidth(200)
        self.fav_btn.setStyleSheet("""
            QPushButton {
                background-color: #FFC107;
                color: #1a2a3a;
                border: none;
                border-radius: 5px;
                font-size: 12pt;
                font-weight: bold;
                padding: 8px 15px;
            }
            QPushButton:hover {
                background-color: #FFB300;
            }
        """)
        self.fav_btn.clicked.connect(self.add_to_favorites)
        fav_btn_layout.addWidget(self.fav_btn)
        
        scroll_layout.addLayout(fav_btn_layout)
        
        history_group = QGroupBox("📜 ИСТОРИЯ РАСЧЁТОВ")
        history_group.setStyleSheet(calc_group.styleSheet())
        
        history_layout = QVBoxLayout(history_group)
        history_layout.setSpacing(10)
        
        self.history_table = QTableWidget()
        self.history_table.setColumnCount(4)
        self.history_table.setHorizontalHeaderLabels(["Материал", "Плотность", "Объём (м³)", "Масса (т)"])
        self.history_table.horizontalHeader().setStretchLastSection(True)
        self.history_table.setAlternatingRowColors(True)
        self.history_table.setMaximumHeight(180)
        history_layout.addWidget(self.history_table)
        
        history_btn_layout = QHBoxLayout()
        history_btn_layout.addStretch()
        
        self.clear_history_btn = QPushButton("🗑️ Очистить историю")
        self.clear_history_btn.clicked.connect(self.clear_history)
        history_btn_layout.addWidget(self.clear_history_btn)
        
        history_layout.addLayout(history_btn_layout)
        
        scroll_layout.addWidget(history_group)
        
        info_frame = QFrame()
        info_frame.setStyleSheet("""
            QFrame {
                background-color: #e8f0fe;
                border: 1px solid #1976D2;
                border-radius: 8px;
                padding: 10px;
            }
        """)
        info_layout = QHBoxLayout(info_frame)
        
        info_icon = QLabel("💡")
        info_icon.setStyleSheet("font-size: 24px;")
        info_layout.addWidget(info_icon)
        
        info_label = QLabel(
            "Плотность материалов может отличаться в зависимости от влажности, "
            "фракции и происхождения. Для точных расчётов используйте данные из "
            "лабораторных анализов или накладных поставщика."
        )
        info_label.setWordWrap(True)
        info_label.setStyleSheet("color: #1a2a3a; font-size: 10pt;")
        info_layout.addWidget(info_label, 1)
        
        scroll_layout.addWidget(info_frame)
        scroll_layout.addStretch()
        
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)
    
    def connect_signals(self):
        self.material_combo.currentIndexChanged.connect(self.update_from_material)
        # НЕ подключаем valueChanged к расчету - только кнопки!
        # Но оставляем для обновления отображения
        self.cubes_spin.valueChanged.connect(self.update_preview)
        self.tons_spin.valueChanged.connect(self.update_preview)
        self.density_spin.valueChanged.connect(self.update_preview)
    
    def update_preview(self):
        """Только обновляет предпросмотр, не сохраняет в историю"""
        pass  # Можно добавить логику предпросмотра если нужно
    
    def update_from_material(self, index):
        if 0 <= index < len(self.MATERIALS):
            material, density = self.MATERIALS[index]
            if density is not None:
                self.density_spin.setValue(density)
    
    def apply_density_from_combo(self):
        self.update_from_material(self.material_combo.currentIndex())
    
    def cubes_to_tons(self):
        try:
            cubes = self.cubes_spin.value()
            density = self.density_spin.value()
            tons = cubes * density
            
            if tons >= 1000:
                result_text = f"{tons:,.2f} т".replace(",", " ")
            else:
                result_text = f"{tons:.2f} т"
            
            self.tons_result.setText(result_text)
            self.last_result = result_text
            self.last_material = self.material_combo.currentText()
            self.last_volume = cubes
            self.last_mass = tons
            self.last_direction = "кубы → тонны"
            
            self.add_to_history(
                self.material_combo.currentText(),
                f"{density:.3f} т/м³",
                f"{cubes:.2f} м³",
                result_text
            )
            
            self.save_to_history()
            
        except Exception as e:
            QMessageBox.critical(self, "Ошибка", f"Ошибка расчёта: {str(e)}")
    
    def tons_to_cubes(self):
        try:
            tons = self.tons_spin.value()
            density = self.density_spin.value()
            if density == 0:
                QMessageBox.warning(self, "Ошибка", "Плотность не может быть равна нулю!")
                return
            
            cubes = tons / density
            
            if cubes >= 1000:
                result_text = f"{cubes:,.2f} м³".replace(",", " ")
            else:
                result_text = f"{cubes:.2f} м³"
            
            self.cubes_result.setText(result_text)
            self.last_result = result_text
            self.last_material = self.material_combo.currentText()
            self.last_volume = cubes
            self.last_mass = tons
            self.last_direction = "тонны → кубы"
            
            self.add_to_history(
                self.material_combo.currentText(),
                f"{density:.3f} т/м³",
                result_text,
                f"{tons:.2f} т"
            )
            
            self.save_to_history()
            
        except Exception as e:
            QMessageBox.critical(self, "Ошибка", f"Ошибка расчёта: {str(e)}")
    
    def save_to_history(self):
        if self.main_window and hasattr(self.main_window, 'history_manager'):
            current_id = datetime.now().strftime("%Y%m%d%H%M%S")
            current_date = datetime.now().strftime("%d.%m.%Y %H:%M")
            
            calculation = {
                "id": current_id,
                "date": current_date,
                "module": "📦 Кубы в тонны",
                "description": f"{self.last_material}, {self.last_volume:.1f} м³ → {self.last_mass:.1f} т ({self.last_direction})",
                "result": self.last_result,
                "params": {
                    "material": self.last_material,
                    "density": self.density_spin.value(),
                    "volume": self.last_volume,
                    "mass": self.last_mass,
                    "direction": self.last_direction
                }
            }
            self.main_window.history_manager.add_to_history(calculation)
            if hasattr(self.main_window, 'favorites_widget'):
                self.main_window.favorites_widget.refresh()
    
    def add_to_favorites(self):
        if not self.last_result:
            QMessageBox.warning(self, "Предупреждение", "Сначала выполните расчёт!")
            return
        
        current_id = datetime.now().strftime("%Y%m%d%H%M%S")
        current_date = datetime.now().strftime("%d.%m.%Y %H:%M")
        
        calculation = {
            "id": current_id,
            "date": current_date,
            "module": "📦 Кубы в тонны",
            "description": f"{self.last_material}, {self.last_volume:.1f} м³ → {self.last_mass:.1f} т",
            "result": self.last_result,
            "params": {
                "material": self.last_material,
                "density": self.density_spin.value(),
                "volume": self.last_volume,
                "mass": self.last_mass,
                "direction": self.last_direction
            }
        }
        
        if self.main_window and hasattr(self.main_window, 'history_manager'):
            if self.main_window.history_manager.add_to_favorites(calculation):
                QMessageBox.information(self, "Готово", "⭐ Расчёт добавлен в избранное!")
                if hasattr(self.main_window, 'favorites_widget'):
                    self.main_window.favorites_widget.refresh()
            else:
                QMessageBox.information(self, "Инфо", "Этот расчёт уже в избранном")
    
    def add_to_history(self, material, density, volume, mass):
        record = (material, density, volume, mass)
        self.history.insert(0, record)
        if len(self.history) > 10:
            self.history = self.history[:10]
        self.update_history_table()
    
    def update_history_table(self):
        self.history_table.setRowCount(len(self.history))
        for row, record in enumerate(self.history):
            for col, value in enumerate(record):
                item = QTableWidgetItem(value)
                item.setTextAlignment(Qt.AlignCenter)
                self.history_table.setItem(row, col, item)
        self.history_table.resizeColumnsToContents()
    
    def clear_history(self):
        self.history = []
        self.history_table.setRowCount(0)
    
    def copy_to_clipboard(self, text):
        clipboard = QApplication.clipboard()
        clipboard.setText(text)
        msg = QMessageBox(self)
        msg.setWindowTitle("Копирование")
        msg.setText(f"✅ Скопировано: {text}")
        msg.setIcon(QMessageBox.Information)
        msg.setStandardButtons(QMessageBox.NoButton)
        msg.show()
        QTimer.singleShot(1500, msg.close)