from datetime import datetime, timedelta
from typing import Optional

from rio import Text, Column, TextStyle, Component, event, TextInput, MultiLineTextInput, Row, Button

from src.ezgg_lan_manager import ConfigurationService, UserService, MailingService
from src.ezgg_lan_manager.components.MainViewContentBox import MainViewContentBox
from src.ezgg_lan_manager.types.User import User
from src.ezgg_lan_manager.types.UserSession import UserSession


class ContactPage(Component):
    # Workaround: Can not reassign this value without rio triggering refresh
    #             Using list to bypass this behavior
    last_message_sent: list[datetime] = [datetime(day=1, month=1, year=2000)]
    user: Optional[User] = None

    e_mail: str = ""
    subject: str = ""
    message: str = ""
    submit_button_is_loading: bool = False
    response_message: str = ""
    is_success: bool = True

    @event.on_populate
    async def on_populate(self) -> None:
        await self.session.set_title(f"{self.session[ConfigurationService].get_lan_info().name} - Kontakt")
        try:
            self.user = await self.session[UserService].get_user(self.session[UserSession].user_id)
        except KeyError:
            self.user = None
        self.e_mail = "" if not self.user else self.user.user_mail

    async def on_send_pressed(self) -> None:
        error_msg = ""
        self.submit_button_is_loading = True
        now = datetime.now()
        if not self.e_mail:
            error_msg = "E-Mail darf nicht leer sein!"
        elif not self.subject:
            error_msg = "Betreff darf nicht leer sein!"
        elif not self.message:
            error_msg = "Nachricht darf nicht leer sein!"
        elif (now - self.last_message_sent[0]) < timedelta(minutes=1):
            error_msg = "Immer mit der Ruhe!"
        if error_msg:
            self.submit_button_is_loading = False
            self.is_success = False
            self.response_message = error_msg
            return

        mail_recipient = self.session[ConfigurationService].get_lan_info().organizer_mail
        msg = (f"Kontaktformular vom {now.strftime('%d.%m.%Y %H:%M')}:\n\n"
               f"Betreff: {self.subject}\n"
               f"Absender: {self.e_mail}\n\n"
               f"Inhalt:\n"
               f"{self.message}\n")
        await self.session[MailingService].send_email("Kontaktformular-Mitteilung", msg, mail_recipient)
        self.last_message_sent[0] = datetime.now()
        self.submit_button_is_loading = False
        self.is_success = True
        self.response_message = "Nachricht erfolgreich gesendet!"

    def build(self) -> Component:
        email_input = TextInput(
            label="E-Mail Adresse",
            text=self.bind().e_mail,
            margin_left=1,
            margin_right=1,
            margin_bottom=1,
            grow_x=True
        )

        subject_input = TextInput(
            label="Betreff",
            text=self.bind().subject,
            margin_left=1,
            margin_right=1,
            margin_bottom=1,
            grow_x=True
        )

        message_input = MultiLineTextInput(
            label="Deine Nachricht an uns",
            text=self.bind().message,
            margin_left=1,
            margin_right=1,
            margin_bottom=1,
            min_height=5
        )

        submit_button = Button(
            content=Text(
                "Absenden",
                style=TextStyle(fill=self.session.theme.success_color, font_size=0.9),
                align_x=0.2
            ),
            align_x=0.9,
            margin_top=2,
            margin_bottom=1,
            shape="rectangle",
            style="major",
            color="primary",
            on_press=self.on_send_pressed,
            is_loading=self.bind().submit_button_is_loading
        )
        return Column(
            MainViewContentBox(
                Column(
                    Text(
                        text="Kontakt",
                        style=TextStyle(
                            fill=self.session.theme.background_color,
                            font_size=1.2
                        ),
                        margin_top=2,
                        margin_bottom=1,
                        align_x=0.5
                    ),
                    email_input,
                    subject_input,
                    message_input,
                    Row(
                        Text(
                            text=self.bind().response_message,
                            style=TextStyle(
                                fill=self.session.theme.success_color if self.is_success else self.session.theme.danger_color,
                                font_size=0.9
                            ),
                            margin_top=2,
                            margin_bottom=1,
                            align_x=0.1
                        ),
                        submit_button,
                    )
                )
            ),
            align_y=0
        )
