import flet as ft
import requests
from pages.view_orders_in_page import ViewOrdersIn
from config import API_BASE_URL

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

        self.delete_dialog = ft.AlertDialog(
            title="Delete order?",
            actions=[
                ft.Button(
                    "Yes", 
                    width=100, 
                    on_click=self.on_confirm_delete_order_click
                ),
                ft.FilledButton(
                    "No", 
                    bgcolor=ft.Colors.GREY,
                    width = 100,
                    on_click=self.on_no_delete_order_btn_click
                )
            ]
        )

    def on_confirm_delete_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_in/{self.selected_delete_order['id']}", headers=headers)
            if response.status_code == 200:
                print('Order deleted!')
        except Exception as e:
            print("Error loading orders:", e)
        self.page.close(self.delete_dialog)
        self.selected_delete_order = None
        self.refresh()

    def on_no_delete_order_btn_click(self, e):
        self.page.close(self.delete_dialog)
        self.selected_delete_order = None

    def view_order(self, order):
        if order:
            self.page.session.set("order_in_id", order['id'])
            self.view_order_page = ViewOrdersIn(self.page, self, self.dashboard)
            self.dashboard.placeholder.content = self.view_order_page.build()
            self.dashboard.placeholder.update()

    def cancel_order(self, order):
        self.selected_delete_order = order
        self.page.open(self.delete_dialog)

    def download_order_file(self, order):
        file = order['file']
        url=f"{API_BASE_URL}/orders_in/files/{file}"
        self.page.launch_url(url)

    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_in/list", headers=headers)
            return response.json() if response.status_code == 200 else []
        except Exception as e:
            print("Error loading orders:", e)

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

    def get_client(self, client_id):
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.get(f"{API_BASE_URL}/clients/{client_id}", headers=headers)
            if response.status_code == 200:
                client = response.json()
                return client['name']
            else:
                return None
        except Exception as e:
            print("Error loading clients:", e)
            return None

    def refresh(self):
        self.orders = self.load_orders()
        self.orders_list.controls.clear()
        for order in self.orders:
            client = self.get_client(order['client_id'])
            buttons = []
            if order.get("file"):
                buttons.append(ft.Button("Download", icon=ft.Icons.DOWNLOAD, on_click=lambda e, o=order: self.download_order_file(o)))
            buttons.append(ft.Button("View", icon=ft.Icons.PICTURE_AS_PDF, on_click=lambda e, o=order: self.view_order(o)))
            buttons.append(ft.Button("Delete", icon=ft.Icons.CANCEL, on_click=lambda e, o=order: self.cancel_order(o)))
            self.orders_list.controls.append(
                ft.Container(
                    content=ft.Row([
                        ft.Column([
                            ft.Text(f"{client}", size=16, weight=ft.FontWeight.BOLD),
                            ft.Text(f"Order Number: {order['order_number']}", size=14),
                        ], expand=True),
                        *buttons
                    ]),
                    padding=10,
                    border=ft.border.all(1, ft.Colors.GREY_300),
                    bgcolor=ft.Colors.BLUE_50,
                    border_radius=10,
                )
            )
        self.page.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_in'] == 1 else False

    def build(self):
        self.refresh()
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Archive Orders In", 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 In", 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
        )