from __future__ import annotations

import tkinter as tk
from tkinter import ttk

from ccma.storage.repository import MemberRepository


class EmailDeliveryChoiceDialog(tk.Toplevel):
    """Shown once per generation action (not per individual e-mail) when the
    repository's delivery mode is "ask" -- lets the board decide per-batch whether
    to send immediately or park the e-mail(s) as a draft for later review."""

    def __init__(self, master: tk.Misc, *, can_send: bool, can_draft: bool):
        super().__init__(master)
        self.result: str | None = None
        self.title("E-Mail-Versand")
        self.transient(master.winfo_toplevel())
        self.resizable(False, False)
        frame = ttk.Frame(self, padding=18)
        frame.pack(fill="both", expand=True)
        ttk.Label(
            frame,
            text="Wie soll mit dieser E-Mail verfahren werden?",
            wraplength=360,
            justify="left",
        ).pack(anchor="w", pady=(0, 14))
        buttons = ttk.Frame(frame)
        buttons.pack(anchor="e")
        ttk.Button(buttons, text="Abbrechen", command=self._cancel).pack(side="left", padx=(0, 8))
        send_button = ttk.Button(buttons, text="Senden", command=self._choose_send)
        send_button.pack(side="left", padx=(0, 8))
        send_button.configure(state="normal" if can_send else "disabled")
        draft_button = ttk.Button(
            buttons, text="Als Entwurf ablegen", style="Accent.TButton", command=self._choose_drafts
        )
        draft_button.pack(side="left")
        draft_button.configure(state="normal" if can_draft else "disabled")
        self.bind("<Escape>", lambda _event: self._cancel())
        self.protocol("WM_DELETE_WINDOW", self._cancel)
        self.after_idle(self.grab_set)

    def _choose_send(self) -> None:
        self.result = "send"
        self.destroy()

    def _choose_drafts(self) -> None:
        self.result = "drafts"
        self.destroy()

    def _cancel(self) -> None:
        self.result = None
        self.destroy()


def resolve_delivery_mode(master: tk.Misc, repository: MemberRepository) -> str | None:
    """Returns the delivery mode to use for the next generated e-mail(s): "local",
    "send" or "drafts" -- or None if the board cancelled out of the "ask every time"
    prompt, in which case the caller should abort without generating anything."""
    settings = repository.get_email_settings()
    mode = settings["delivery_mode"]
    if mode in {"local", "send", "drafts"}:
        return mode
    dialog = EmailDeliveryChoiceDialog(
        master, can_send=bool(settings["smtp_host"]), can_draft=bool(settings["imap_host"])
    )
    master.wait_window(dialog)
    return dialog.result
