import flet as ft
from flet_webview import WebView
from pages.send_email_page import SendEmail
import requests
from config import API_BASE_URL

class ViewPage:
    def __init__(self, page: ft.Page, pdf_name, order_page, dashboard, order_id):
        self.page = page
        self.pdf_name = pdf_name
        self.order_page = order_page
        self.dashboard = dashboard
        self.order_id = order_id
        self.send_email = SendEmail(self.page, self, self.dashboard, self.order_id)
        self.view_content = WebView(url=f"{API_BASE_URL}/orders/pdfs/{self.pdf_name}", expand=True)
        self.send_btn = ft.FilledButton("Send as Email", on_click=self.on_send_email_btn_click)
        self.row_btn = ft.Row([])
        if self.get_credentials():
            self.row_btn.controls.append(self.send_btn)

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

    def on_send_email_btn_click(self, e):
        self.dashboard.placeholder.content = self.send_email.build()
        self.dashboard.placeholder.update()

    def get_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)
        return response.json() if response.status_code == 200 else None

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Order", 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
                    ),
                    self.view_content,
                    self.row_btn,
                ]
            )
        )