import flet as ft
import requests
import json
from config import API_BASE_URL

class SendEmail:
    def __init__(self, page: ft.Page, view_page, dashboard, order_id):
        self.page = page
        self.view_page = view_page
        self.dashboard = dashboard
        self.order_id = order_id
        self.smtp_password = ft.TextField(label="PASSWORD")
        self.message = ft.TextField(label="Message", multiline=True, min_lines=10, max_lines=20, expand=True)
        self.send = ft.ElevatedButton("Send", width=150, on_click=self.send_email)
        self.order = self.get_order()
        if self.order:
            transporter = self.get_transporter(self.order['transporter_id'])
            self.to_email = transporter['email']
        self.smtp_host = ''
        self.smtp_port = ''
        self.from_email = ''

    def on_go_back_btn_click(self, e):
        self.dashboard.placeholder.content = self.view_page.build()
        self.dashboard.placeholder.update()

    def send_email(self, e):
        user_id = self.page.session.get("user_id")
        user = self.get_user()
        transporter_data = {
            "to_email":self.to_email,
            "subject":self.order['order_number'],
            "body":self.message.value,
            "filename":f'order_{user_id}_{self.order['order_number']}.pdf',
            "smtp_host":self.smtp_host,
            "smtp_port":self.smtp_port,
            "smtp_user":self.from_email,
            "smtp_pass": self.smtp_password.value,
        }
        self.send_email_custom(transporter_data)
        user_data = {
            "to_email":user['email'],
            "subject":self.order['order_number'],
            "body":self.message.value,
            "filename":f'order_{user_id}_{self.order['order_number']}.pdf',
            "smtp_host":self.smtp_host,
            "smtp_port":self.smtp_port,
            "smtp_user":self.from_email,
            "smtp_pass": self.smtp_password.value,
        }
        self.send_email_custom(user_data)
    
    def send_email_custom(self, data):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(f"{API_BASE_URL}/orders/send-email/custom", headers=headers, data=json.dumps(data))
        return response.json() if response.status_code == 200 else None

    def get_transporter(self, id):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        user_id = self.page.session.get("user_id")
        response = requests.get(f"{API_BASE_URL}/transporters/{id}", headers=headers)
        return response.json() if response.status_code == 200 else None

    def get_order(self):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(f"{API_BASE_URL}/orders/{self.order_id}", headers=headers)
        return response.json() if response.status_code == 200 else None
    
    def get_user(self):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(f"{API_BASE_URL}/profile/", headers=headers)
        return response.json() if response.status_code == 200 else None
    
    def get_email_credentials(self):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(f"{API_BASE_URL}/profile/email", headers=headers)
        credentials = response.json()
        self.smtp_host = credentials['smtp_host']
        self.smtp_port = credentials['smtp_port']
        self.from_email = credentials['smtp_user']

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Send E-mail", size=24, weight=ft.FontWeight.BOLD),
                            ft.Button("Back", icon=ft.Icons.ARROW_BACK_IOS_NEW, on_click=self.on_go_back_btn_click)
                        ],
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                    ),
                    ft.Row(
                        [
                            ft.Column(
                                [
                                    ft.Text("Please insert email password:"),
                                    self.smtp_password,
                                ]
                            ),
                            self.send
                        ],
                        vertical_alignment=ft.CrossAxisAlignment.END,
                        expand=True
                    ),
                    self.message
                ],
                alignment=ft.MainAxisAlignment.START,
                scroll=ft.ScrollMode.ADAPTIVE,
                expand=True
            ),
            expand=True
        )