import flet as ft
import requests
from pages.view_page import ViewPage
from pages.orders_edit_page import OrdersEditPage
from config import API_BASE_URL

class ArchivePage:
    def __init__(self, page:ft.Page, dashboard, order_page):
        self.page = page
        self.dashboard = dashboard
        self.orders = []
        self.orders_list = ft.Column(spacing=10, expand=True, scroll=ft.ScrollMode.ADAPTIVE,)
        self.order_page = order_page
        self.selected_cancel_order = None

        self.cancel_dialog = ft.AlertDialog(
            title="Cancel order?",
            actions=[
                ft.Button(
                    "Yes", 
                    width=100, 
                    on_click=self.on_confirm_calcel_order_click
                ),
                ft.FilledButton(
                    "No", 
                    bgcolor=ft.Colors.GREY,
                    width = 100,
                    on_click=self.on_no_cancel_order_btn_click
                )
            ]
        )

    def refresh(self):
        self.orders = self.load_orders()
        self.orders_list.controls.clear()
        for order in self.orders:
            self.orders_list.controls.append(
                ft.Container(
                    content=ft.Row([
                        ft.Column([
                            ft.Text(f"{order['order_number']}", size=16, weight=ft.FontWeight.BOLD),
                        ], expand=True),
                        ft.Button("View",icon=ft.Icons.PICTURE_AS_PDF, on_click=lambda e, o=order: self.view_order(o)),
                        *([
                            ft.Button("Edit", icon=ft.Icons.EDIT, on_click=lambda e, o=order: self.edit_order(o)),
                            ft.Button("Cancel", icon=ft.Icons.CANCEL, on_click=lambda e, o=order: self.cancel_order(o))
                        ] if order['status'] == 'active' else [])
                    ]),
                    padding=10,
                    border=ft.border.all(1, ft.Colors.GREY_300),
                    bgcolor=ft.Colors.BLUE_50,
                    border_radius=10,
                )
            )
        self.page.update()

    def load_orders(self):
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.get(f"{API_BASE_URL}/orders/list", headers=headers)
            return response.json() if response.status_code == 200 else []
        except Exception as e:
            print("Error loading orders:", e)

    def view_order(self, order):
        #print(order)
        user_id = self.page.session.get("user_id")
        user = self.get_user()
        if user['user_role'] == 'company_user':
            user_id = user['company_id']
        pdf_name = f'order_{user_id}_{order['order_number']}.pdf'
        #print(pdf_name)
        view_page = ViewPage(self.page, pdf_name, self.order_page, self.dashboard, order['id'])
        self.dashboard.placeholder.content = view_page.build()
        self.dashboard.placeholder.update()

    def edit_order(self, order):
        self.page.session.set('order_id', order['id'])
        edit_order = OrdersEditPage(self.page, self.dashboard, self)
        self.dashboard.placeholder.content = edit_order.build()
        self.dashboard.placeholder.update()

    def cancel_order(self, order):
        self.selected_cancel_order = order
        self.page.open(self.cancel_dialog)

    def on_confirm_calcel_order_click(self, e):
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.delete(
                f"{API_BASE_URL}/orders/cancel/{self.selected_cancel_order['id']}",
                headers=headers
            )
            if response.status_code != 200:
                print("Failed to cancel order:", response.status_code)
        except Exception as e:
            print("Error cancelling order:", e)

        self.page.close(self.cancel_dialog)
        self.selected_cancel_order = None
        self.refresh()  # Optional: Refresh the list

    def on_no_cancel_order_btn_click(self, e):
        self.selected_cancel_order = None
        self.page.close(self.cancel_dialog)

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

    def get_client_access(self):
        token = self.page.client_storage.get("token")
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(f"{API_BASE_URL}/profile/", headers=headers, timeout=10)
        user = response.json()
        if user['user_role'] == 'user':
            return True
        else:
            id = self.page.session.get("user_id")
            response = requests.get(f"{API_BASE_URL}/company_user/access/{id}", headers=headers)
            return True if response.json()['orders_out'] == 1 else False
        
    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, timeout=10)
        return response.json()

    def build(self):
        self.refresh()
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Archive Orders Out", 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.orders_list
                ]
            )
        ) if self.get_client_access() else ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Archive Orders Out", size=24, weight=ft.FontWeight.BOLD),
                        ],
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                    ),
                    ft.Row(
                        [
                            ft.Text(
                                "You do not have access to this page content", 
                                size=24, 
                                weight=ft.FontWeight.BOLD,
                                color=ft.Colors.RED
                            )
                        ],
                        alignment=ft.MainAxisAlignment.CENTER
                    ),
                    ft.Text("")
                ],
                alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                expand=True
            ),
            expand=True
        )