from qgis.PyQt import QtWidgets, QtCore
from datetime import datetime
from ..utils.task_list import TasksReview
from ..utils.api import APIGetOrderDetails
from ..utils.document_list import DocumentList
from ..utils.messaging_widget import MessagingWidget


class OrderDetailDialog(QtWidgets.QDialog):
    STATUS_MAP = {
        "draft": "Entwurf",
        "inTender": "In Ausschreibung",
        "contracted": "Beauftragt",
        "inDevelopment": "In Bearbeitung",
        "inReview": "Zur Abnahme",
        "completed": "Abgeschlossen"
    }

    def __init__(self, parent=None, cognito_session=None, order_id=None, plan_id=None):
        super().__init__(parent)
        self.cognito_session = cognito_session
        self.order_id = order_id
        self.plan_id = plan_id
        self.order = {}

        self.setWindowTitle(f"Auftrag: {plan_id or order_id}")
        self.resize(1200, 800)

        self.layout = QtWidgets.QVBoxLayout(self)

        # ---- Store detail labels only (no layout yet!) ----
        self.detail_labels = {}
        for label_text in ["Auftragsnummer", "Auftragsbezeichnung", "Gemeinde", "Erstellt am", "Fortschritt"]:
            self.detail_labels[label_text] = QtWidgets.QLabel("-")

        self.dynamic_area = QtWidgets.QVBoxLayout()
        self.layout.addLayout(self.dynamic_area)

        self.load_order_details()

    # -------------------------------------------------------------

    def load_order_details(self):
        if not (self.cognito_session and self.cognito_session.access_token):
            QtWidgets.QMessageBox.critical(self, "Fehler", "Keine gültige Authentifizierung vorhanden.")
            return

        try:
            self.order = APIGetOrderDetails(self.cognito_session, self.order_id)

            stage = self.order.get("stage", "-")
            self.detail_labels["Auftragsnummer"].setText(self.order.get("planId", "-"))
            self.detail_labels["Auftragsbezeichnung"].setText(
                (self.order.get("planDetails") or {}).get("name", "-")
            )
            self.detail_labels["Gemeinde"].setText(
                ((self.order.get("planDetails") or {}).get("community") or {}).get("name", "-")
            )
            created_at = self._format_timestamp(self.order.get("createdAt"))
            self.detail_labels["Erstellt am"].setText(created_at)
            self.detail_labels["Fortschritt"].setText(self.STATUS_MAP.get(stage, stage))

            reviews = self.order.get("reviewDetails", [])
            reviews = sorted(reviews, key=lambda x: int(x.get("version", 0)), reverse=True)

            self._build_dynamic_area(stage, reviews)

        except Exception:
            return

    # -------------------------------------------------------------

    def _build_dynamic_area(self, stage: str, reviewDetails: list):

        # Clear old widgets
        while self.dynamic_area.count():
            item = self.dynamic_area.takeAt(0)
            if item.widget():
                item.widget().deleteLater()

        # Scrollbereich (LEFT SIDE)
        scroll = QtWidgets.QScrollArea()
        scroll.setStyleSheet("""
            QGroupBox {
                background-color: #fff;
                border-radius:8px;
                border:none;
                margin:0px;
                padding:6px 0px;
                color:999;

            }
            QGroupBox {
                background-color: #fff;
                border-radius:8px;
                margin:0px;
                border:none;
                padding:6px 0px;
                color:999;

            }
            QPushButton {
                cursor:pointer; 
                border: 1px solid #000; 
                padding: 4px 12px; 
                margin:2px; 
                font-size:12px;
                height:24px;
                border-radius:6px;
            }
            QPushButton:hover {
                background-color: #000;
                color: white;
                border: 1px solid #000;
            }
            QPushButton:pressed {
                background-color: #333;
                color: white;
            }
        """)
        scroll.setWidgetResizable(True)
        scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        scroll_content = QtWidgets.QWidget()
        scroll_layout = QtWidgets.QVBoxLayout(scroll_content)

        for idx, review in enumerate(reviewDetails):
            box = QtWidgets.QGroupBox()
            inner_widget = QtWidgets.QWidget()
            inner = QtWidgets.QVBoxLayout(inner_widget)

            status = review.get("status", "")
            created = self._format_timestamp(review.get("creationDate"))

            status_version = QtWidgets.QLabel(f"Version {review.get('version', '-')}")
            status_version.setStyleSheet("font-weight: bold;")
            inner.addWidget(status_version)

            status_label = QtWidgets.QLabel()
            if status == "active" and stage == "inReview":
                status_label.setText("Die Bearbeitung Ihres Auftrags wurde abgeschlossen und kann geprüft werden.")
            elif status == "rejected":
                status_label.setText("Diese Abnahme wurde bereits abgelehnt.")
                status_label.setStyleSheet("color: #dc2626; font-weight: bold;")
            elif status == "cancel":
                status_label.setText("Diese Abnahme wurde zurückgezogen.")
                status_label.setStyleSheet("color: #d97706; font-weight: bold;")
            elif idx == 0:
                status_label.setText("Diese Abnahme wurde abgenommen.")
                status_label.setStyleSheet("color: #16a34a; font-weight: bold;")
            else:
                status_label.setText("Diese Abnahme ist abgelehnt oder zurückgezogen.")
                status_label.setStyleSheet("color: #d97706; font-weight: bold;")

            inner.addWidget(status_label)
            inner.addWidget(QtWidgets.QLabel(f"Erstellt am: {created}"))

            doc_list = DocumentList(
                self.cognito_session,
                self.order_id,
                review.get("reviewId", ""),
                self,
                plan_id=self.order.get("planId"),
                user_status=self.order.get("companyStatus", "")
            )
            inner.addWidget(doc_list)
            tasks_widget = TasksReview(
                order_id=self.order_id,
                company_id=self.order.get("companyId", ""),
                user_status=self.order.get("companyStatus", ""),
                order_stage=stage,
                selected_version_status=review.get("status", ""),
                cognito_session=self.cognito_session
            )
            inner.addWidget(tasks_widget)

            outer_layout = QtWidgets.QVBoxLayout()
            outer_layout.addWidget(inner_widget)
            box.setLayout(outer_layout)
            scroll_layout.addWidget(box)

        scroll_layout.addStretch()
        scroll.setWidget(scroll_content)

        # -----------------------------
        # Splitter
        # -----------------------------
        splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
        splitter.setChildrenCollapsible(False)

        # =========================
        # LEFT SIDE
        # =========================
        left_container = QtWidgets.QWidget()
        left_layout = QtWidgets.QVBoxLayout(left_container)
 

        title = QtWidgets.QLabel("Abnahmeprotokoll")
        title.setStyleSheet("font-size:16px;")
        left_layout.addWidget(title)
        left_layout.addWidget(scroll)

        splitter.addWidget(left_container)

        # =========================
        # RIGHT SIDE (NEW STRUCTURE)
        # =========================
        right_container = QtWidgets.QWidget()
        right_container.setStyleSheet("background:#fff;")
        right_layout = QtWidgets.QVBoxLayout(right_container)
        right_layout.setContentsMargins(0, 0, 0, 0)


        

        # ---- Detail Box ----
        details_box = QtWidgets.QGroupBox("")
        details_box.setStyleSheet("""
            QGroupBox {
                background-color: #fff;
                border-radius:8px;
                margin:0px;
                padding:6px 0px;
                color:999;

            }
        """)  
        title2 = QtWidgets.QLabel("Auftragsdetails")
        title2.setStyleSheet("font-size:16px; margin-top:10px; padding: 5px; ")
        right_layout.addWidget(title2)

        
        details_layout = QtWidgets.QVBoxLayout(details_box)
        
        
        
        
        for label_text, value_label in self.detail_labels.items():
            row = QtWidgets.QHBoxLayout()
            row.setContentsMargins(0, 0, 0, 0)
            row.addWidget(QtWidgets.QLabel(f"{label_text}:"))
            row.addWidget(value_label)
            details_layout.addLayout(row)
        right_layout.addWidget(details_box)



        # ---- Messaging ----
        if stage in ["contracted", "inDevelopment", "inReview", "completed"]:
            messaging = MessagingWidget(
                cognito_session=self.cognito_session,
                order_id=self.order_id,
                link_id=None,
                link_type="all",
                company_id=self.order.get("companyId", ""),
                stage=stage
            )
            right_layout.addWidget(messaging)
        else:
            right_layout.addWidget(QtWidgets.QWidget())

        right_layout.addStretch()

        splitter.addWidget(right_container)

        splitter.setStretchFactor(0, 1)
        splitter.setStretchFactor(1, 1)

        self.dynamic_area.addWidget(splitter)

        QtCore.QTimer.singleShot(0, lambda: splitter.setSizes([600, 600]))

    # -------------------------------------------------------------

    def _format_timestamp(self, ts):
        if not ts or ts == "-":
            return "-"
        try:
            dt = datetime.fromtimestamp(int(ts) / 1000)
            return dt.strftime("%d.%m.%Y %H:%M")
        except Exception:
            return str(ts)

    def reject_review(self, review_id):
        QtWidgets.QMessageBox.information(self, "Abgelehnt", f"Review {review_id} wurde abgelehnt.")
        self.load_order_details()

    def complete_review(self, review_id):
        QtWidgets.QMessageBox.information(self, "Abgenommen", f"Review {review_id} wurde abgenommen.")
        self.load_order_details()

    def accept_order(self):
        pass