# -*- coding: utf-8 -*-
# hub/ticket/ui/details/task_details_actions.py

"""Отдельный модуль действий экрана деталей Ticket."""

from __future__ import annotations

from application.ticket_application_api import TicketApplicationApi
from domain import TicketDocumentSnapshot, TicketTaskSnapshot
from ui.dialogs import (
    AcceptanceDialog,
    DiagnosticReportDialog,
    RepairReportDialog,
    SpecialistDialog,
    TaskRefusalDialog,
)
from ui.ticket_message_dialog import TicketMessageDialog


class TaskDetailsActions:
    """Обёртка над application-командами для details-экрана."""

    def __init__(self, application: TicketApplicationApi):
        self._application = application

    def assign_specialist(
        self,
        task: TicketTaskSnapshot,
        parent=None,
    ) -> TicketTaskSnapshot | None:
        dialog = SpecialistDialog(
            specialists=self._application.list_specialists(),
            parent=parent,
        )
        if dialog.exec() != dialog.DialogCode.Accepted:
            return None
        specialist_name = dialog.selected_specialist.strip()
        if not specialist_name:
            self._show_warning(parent, "Имя специалиста не указано.")
            return None
        snapshot = self._application.assign_specialist(task.task_id, specialist_name)
        if snapshot is None:
            self._show_warning(parent, "Не удалось назначить специалиста.")
        return snapshot

    def sign_diagnostic(
        self,
        task: TicketTaskSnapshot,
        parent=None,
    ) -> TicketDocumentSnapshot | None:
        dialog = DiagnosticReportDialog(task, parent=parent)
        if dialog.exec() != dialog.DialogCode.Accepted:
            return None
        try:
            return self._application.create_diagnostic_report(
                task.task_id,
                **dialog.build_payload(),
            )
        except ValueError as exc:
            self._show_warning(parent, str(exc))
            return None

    def sign_repair(
        self,
        task: TicketTaskSnapshot,
        parent=None,
    ) -> TicketDocumentSnapshot | None:
        dialog = RepairReportDialog(task, parent=parent)
        if dialog.exec() != dialog.DialogCode.Accepted:
            return None
        try:
            return self._application.create_repair_report(
                task.task_id,
                **dialog.build_payload(),
            )
        except ValueError as exc:
            self._show_warning(parent, str(exc))
            return None

    def sign_acceptance(
        self,
        task: TicketTaskSnapshot,
        parent=None,
    ) -> TicketDocumentSnapshot | None:
        dialog = AcceptanceDialog(task, parent=parent)
        if dialog.exec() != dialog.DialogCode.Accepted:
            return None
        try:
            return self._application.create_acceptance_report(
                task.task_id,
                **dialog.build_payload(),
            )
        except ValueError as exc:
            self._show_warning(parent, str(exc))
            return None

    def archive_task(
        self,
        task: TicketTaskSnapshot,
        parent=None,
    ) -> TicketTaskSnapshot | None:
        answer = TicketMessageDialog.ask_confirmation(
            parent=parent,
            title="Архивация задачи",
            message=f"Переместить задачу #{task.sequence_number or task.task_id} в архив?",
            accept_text="В архив",
            reject_text="Отмена",
        )
        if not answer:
            return None
        snapshot = self._application.archive_task(task.task_id)
        if snapshot is None:
            self._show_warning(parent, "Не удалось переместить задачу в архив.")
        return snapshot

    def refuse_task(
        self,
        task: TicketTaskSnapshot,
        parent=None,
    ) -> TicketTaskSnapshot | None:
        dialog = TaskRefusalDialog(task, parent=parent)
        if dialog.exec() != dialog.DialogCode.Accepted:
            return None
        refusal_reason = dialog.refusal_reason
        if not refusal_reason:
            self._show_warning(parent, "Причина отказа не указана.")
            return None
        snapshot = self._application.refuse_task(task.task_id, refusal_reason)
        if snapshot is None:
            self._show_warning(parent, "Не удалось перевести задачу в отказ.")
        return snapshot

    @staticmethod
    def _show_warning(parent, text: str) -> None:
        TicketMessageDialog.show_warning(parent, "Ticket", text)
