from __future__ import annotations

from pathlib import Path

from PySide6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QTextEdit,
    QPushButton, QMessageBox
)

from mi100.repository import Repo
from mi100.services.email_service import send_email_with_attachment

BTN_GREEN = (
    "QPushButton{background:#4FAF7A;color:#FFFFFF;border:1px solid #459E6E;"
    "border-radius:4px;padding:4px 10px;font-weight:600;}"
    "QPushButton:hover{background:#459E6E;}"
)

BTN_OUTLINE = (
    "QPushButton{background:white;color:#0F172A;border:1px solid #D7D7D7;"
    "border-radius:4px;padding:4px 10px;font-weight:600;}"
    "QPushButton:hover{background:#F8FAFC;}"
)


class EmailSendDialog(QDialog):
    def __init__(
        self,
        repo: Repo,
        *,
        client_id: int,
        document_id: int,
        recipient_email: str,
        subject: str,
        body: str,
        attachment_path: str,
        document_kind: str = '',
        recipient_kind: str = 'client',
        recipient_name: str = '',
        document_number: str = '',
        parent=None,
    ):
        super().__init__(parent)
        self.repo = repo
        self.client_id = int(client_id)
        self.document_id = int(document_id)
        self.attachment_path = str(attachment_path or '')
        self.document_kind = document_kind or ''
        self.recipient_kind = recipient_kind or 'client'
        self.recipient_name = recipient_name or ''
        self.document_number = document_number or ''
        self.setWindowTitle('Відправити на Email')
        self.resize(760, 560)

        root = QVBoxLayout(self)
        root.setContentsMargins(14, 14, 14, 14)
        root.setSpacing(10)

        lbl_to = QLabel('Email одержувача')
        lbl_to.setStyleSheet('font-weight:700; border:none; background:transparent; padding:0; margin:0;')
        root.addWidget(lbl_to)
        self.to_edit = QLineEdit(recipient_email)
        root.addWidget(self.to_edit)

        lbl_subject = QLabel('Тема листа')
        lbl_subject.setStyleSheet('font-weight:700; border:none; background:transparent; padding:0; margin:0;')
        root.addWidget(lbl_subject)
        self.subject_edit = QLineEdit(subject)
        root.addWidget(self.subject_edit)

        lbl_body = QLabel('Текст листа')
        lbl_body.setStyleSheet('font-weight:700; border:none; background:transparent; padding:0; margin:0;')
        root.addWidget(lbl_body)
        self.body_edit = QTextEdit()
        self.body_edit.setPlainText(body or self._compose_default_body())
        root.addWidget(self.body_edit, 1)

        attach_name = Path(self.attachment_path).name if self.attachment_path else '—'
        attach_lbl = QLabel(f'Вкладення: {attach_name}')
        attach_lbl.setStyleSheet('font-weight:700; border:none; background:transparent; padding:0; margin:0;')
        root.addWidget(attach_lbl)

        actions = QHBoxLayout()
        actions.addStretch(1)
        btn_cancel = QPushButton('Скасувати')
        btn_cancel.clicked.connect(self.reject)
        actions.addWidget(btn_cancel)
        btn_send = QPushButton('Надіслати')
        btn_send.setStyleSheet(BTN_GREEN)
        btn_send.clicked.connect(self._send)
        actions.addWidget(btn_send)
        root.addLayout(actions)

    def _template_key(self) -> str:
        if self.recipient_kind == 'actor':
            return 'actor_report'
        mapping = {
            'INVOICE': 'client_invoice',
            'ACT': 'client_act',
            'CLIENT_REPORT': 'client_report',
            'ACTOR_REPORT': 'actor_report',
            'REPORT': 'client_report',
        }
        return mapping.get(self.document_kind, 'client_report')

    def _compose_default_body(self) -> str:
        return self.repo.build_email_body(
            template_key=self._template_key(),
            doc_number=self.document_number,
            recipient_name=self.recipient_name,
        )
    def _send(self) -> None:
        settings = self.repo.get_email_settings()
        required = ['smtp_host', 'smtp_port', 'smtp_sender_email']
        missing = [k for k in required if not str(settings.get(k, '')).strip()]
        if missing:
            QMessageBox.warning(self, 'Налаштування email', 'Заповніть SMTP-налаштування в Налаштуваннях студії.')
            return
        to_email = self.to_edit.text().strip()
        if not to_email:
            QMessageBox.warning(self, 'Email', 'Вкажіть email одержувача.')
            return
        try:
            send_email_with_attachment(
                smtp_host=str(settings.get('smtp_host', '')).strip(),
                smtp_port=int(str(settings.get('smtp_port', '587') or '587')),
                smtp_username=str(settings.get('smtp_username', '')).strip(),
                smtp_password=str(settings.get('smtp_password', '')),
                sender_name=str(settings.get('smtp_sender_name', '')).strip(),
                sender_email=str(settings.get('smtp_sender_email', '')).strip(),
                recipient_email=to_email,
                subject=self.subject_edit.text().strip(),
                body=self.body_edit.toPlainText().strip(),
                attachment_path=self.attachment_path,
            )
            if self.client_id > 0:
                self.repo.add_email_history(
                    client_id=self.client_id,
                    document_id=self.document_id,
                    sent_to_email=to_email,
                    subject_snapshot=self.subject_edit.text().strip(),
                    body_snapshot=self.body_edit.toPlainText().strip(),
                )
        except Exception as e:
            QMessageBox.critical(self, 'Помилка email', f'Не вдалося надіслати лист.\n\n{e}')
            return
        self.accept()
