import flet as ft
from dbActions.orders import Orders
from dbActions.users import Users
from dbActions.products import Products
from helpers.default_user import DefaultUser
from helpers.emails import send_gmail

class OrdersPage:
    def __init__(self, page: ft.Page):
        self.page = page
        self.orders = Orders()
        self.users = Users()
        self.products = Products()
        self.selected_user = None
        self.selected_order = None
        self.selected_order_products = None
        self.original_status = None
        self.customer_email = None
        self.default_user = DefaultUser(self.page)
        self.header = ft.Row(
            [
                ft.Text(
                    "Comenzi", 
                    weight=ft.FontWeight.BOLD, 
                    size=18
                ),
            ],
            alignment=ft.MainAxisAlignment.START
        )
        self.all_orders = self.orders.get_orders()
        self.all_orders = self.all_orders[::-1]
        self.oll_orders_list = ft.ListView(
            controls=self.create_list(self.all_orders, self.on_order_click),
            spacing=10,
            expand=3,
            height=700
        )
        self.fileters = ft.RadioGroup(
            content=ft.Row(
                [
                    ft.Radio(value="on_hold", label="In asteptare"),
                    ft.Radio(value="new", label="Noua"),
                    ft.Radio(value="in_progress", label="In lucru"),
                    ft.Radio(value="completed", label="Complete"),
                    ft.Radio(value="all", label="Toate")
                ]
            ),
            on_change=self.on_filter_change
        )
        self.name = ft.Text()
        self.email = ft.Text()
        self.phone = ft.Text()
        self.address = ft.Text()
        self.total_pay = ft.Text(weight=ft.FontWeight.BOLD)
        self.products_column = ft.Column([])
        self.status = ft.Text()
        self.date = ft.Text()
        self.buttons_state = ft.RadioGroup(
            content=ft.Row(
                [
                    ft.Radio(value="on_hold", label="In asteptare"),
                    ft.Radio(value="new", label="Noua"),
                    ft.Radio(value="in_progress", label="In lucru"),
                    ft.Radio(value="completed", label="Complete"),
                ],
            ),
            on_change=self.on_radio_value_change
        )
        self.total_row = ft.Row(
                    [
                        ft.Text(
                            value="Total platit", 
                            weight=ft.FontWeight.BOLD, 
                        ),
                        self.total_pay
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                )

        self.order_details =  ft.Column(
            [
                ft.Text(
                    value="Detalii utilizator", 
                    weight=ft.FontWeight.BOLD, 
                    size=18
                ),
                ft.Row(
                    [
                        ft.Text(
                            value="Nume si prenume", 
                            weight=ft.FontWeight.BOLD, 
                        ),
                        self.name
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                ft.Row(
                    [
                        ft.Text(
                            value="E-mail", 
                            weight=ft.FontWeight.BOLD, 
                        ),
                        self.email
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                ft.Row(
                    [
                        ft.Text(
                            value="Telefon", 
                            weight=ft.FontWeight.BOLD, 
                        ),
                        self.phone
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                ft.Row(
                    [
                        ft.Text(
                            value="Adresa", 
                            weight=ft.FontWeight.BOLD, 
                        ),
                        self.address
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                ft.Row(
                    [
                        ft.Text(
                            value="Status", 
                            weight=ft.FontWeight.BOLD, 
                        ),
                        self.status,
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                self.total_row,
                ft.Row(
                    [
                        ft.Text(
                            "Data comanda",
                            weight=ft.FontWeight.BOLD
                        ),
                        self.date 
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                ft.Divider(),
                ft.Text(
                    value="Produse",
                    weight=ft.FontWeight.BOLD, 
                    size=18
                ),
                self.products_column,
                ft.Divider(),
                ft.Row(
                    [
                        self.buttons_state,
                        ft.Button("Sterge", icon = ft.Icons.DELETE, on_click=self.on_order_delete_btn_click)
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                )
            ],
            expand=True,
            scroll=ft.ScrollMode.ADAPTIVE
        )

        self.order_details_placeholder = ft.Container(
            expand=7,
            padding=10,
            border_radius=10,
        )

        self.message_field = ft.TextField(
            label="Scrie un mesaj clientului",
            min_lines=3,
            max_lines=5,
            multiline=True
        )

        self.change_state_dialog = ft.AlertDialog(
            title=ft.Text("Modifica statusul"),
            content=self.message_field,
            actions=[
                ft.FilledButton(
                    "Da", 
                    on_click=self.on_change_state_btn_click
                ),
                ft.FilledButton(
                    "Nu",
                    on_click=self.on_cancel_state_btn_click,
                    bgcolor=ft.Colors.GREY
                )
            ]
        )

        self.delete_order_dialog = ft.AlertDialog(
            title=ft.Text("Sertgeti?"),
            actions=[
                ft.FilledButton(
                    "Da", 
                    on_click=self.on_confirm_delete_order
                ),
                ft.FilledButton(
                    "Nu",
                    on_click=self.on_cancel_delete_order_btn_click,
                    bgcolor=ft.Colors.GREY
                )
            ]
        )

    def on_order_delete_btn_click(self, e):
        self.page.open(self.delete_order_dialog)

    def on_confirm_delete_order(self, e):
        self.orders.remove_order(self.selected_order['id'])
        self.all_orders = self.orders.get_orders()[::-1]
        self.oll_orders_list.controls = self.create_list(self.all_orders, self.on_order_click)
        self.oll_orders_list.update()
        self.selected_order = None
        self.order_details_placeholder.content = None
        self.order_details_placeholder.update()
        self.page.close(self.delete_order_dialog)

    def on_cancel_delete_order_btn_click(self, e):
        self.page.close(self.delete_order_dialog)

    def on_radio_value_change(self, e):
        self.page.open(self.change_state_dialog)

    def on_change_state_btn_click(self, e):
        self.page.close(self.change_state_dialog)
        status = self.buttons_state.value
        self.orders.update_order_status(status, self.selected_order['id'])
        print(status)
        self.all_orders = self.orders.get_orders()
        self.all_orders = self.all_orders[::-1]
        self.oll_orders_list.controls.clear()
        self.oll_orders_list.controls = self.create_list(self.all_orders, self.on_order_click)
        self.oll_orders_list.update()
        self.order_details_placeholder.content = None
        self.order_details_placeholder.update()
        message = self.message_field.value
        self.message_field.value = ''
        self.message_field.update()
        print(message)
        email = self.customer_email
        status_values = {
            "on_hold":"in asteptare",
            "new": "noua",
            "in_progress":"in lucru",
            "completed": "la curier",
        }
        send_gmail(
            to_email=email,
            subject=f"Comanda cumneavoastra este: {status_values[status]}",
            body=message
        )

    def on_cancel_state_btn_click(self, e):
        self.buttons_state.value = self.original_status
        self.buttons_state.update()
        self.page.close(self.change_state_dialog)

    def get_total_pay(self):
        sume = 0
        print (self.selected_order_products)
        if self.selected_order_products:
            for product in self.selected_order_products:
                sume += (product['price'] - product['price']*product['discount']/100)
            print(sume)
        return sume

    def on_order_click(self, item):
        self.products_column.controls.clear()
        self.order_details_placeholder.content = None
        self.order_details_placeholder.content = self.order_details
        self.order_details_placeholder.bgcolor=ft.Colors.BROWN_50
        try:
            self.order_details_placeholder.update()
        except:
            print('ERROR Unable to update the Order Details Placeholder')
        print("order item", item)
        self.selected_user = self.users.get(item['user_id'])
        if self.selected_user == None:
            self.selected_user = self.default_user.default_user
        self.selected_order = item
        products = self.orders.get_order_products(item['id'])
        self.selected_order_products = []
        if products:
            for product in products:
                prod = self.products.get(product['prdouct_id'])
                if prod:
                    prod['pices'] = product['quantity']
                    self.selected_order_products.append(prod)
                    print(prod)
        
        self.name.value = self.selected_user['name'] if '@default.com' not in self.selected_user['email'] else 'Anonim user'
        self.name.update()
        self.email.value = self.selected_user['email']
        self.email.update()
        self.customer_email = self.selected_user['email']
        self.address.value = self.selected_user['address'] if '@default.com' not in self.selected_user['email'] else 'Anonim user'
        self.address.update()
        self.phone.value = self.selected_user['phone'] if '@default.com' not in self.selected_user['email'] else 'Anonim user'
        self.phone.update()
        self.status.value = self.selected_user['status']
        self.status.update()
        #self.date.value = item['']
        for product in self.selected_order_products:
            name_label = ft.Text(
                "Denumire produs",
                weight=ft.FontWeight.BOLD
                )
            name = ft.Text(product['name'])
            name_row = ft.Row(
                [
                    name_label,
                    name
                ]
            )
            image = ft.Image(
                src=product['image'],
                width=120,
                height=120,
                fit=ft.ImageFit.CONTAIN
            )
            quantity_label = ft.Text("Cantitate")
            quantity = ft.Text(product['quantity'])
            pices_label = ft.Text("Numar bucati")
            pices = ft.Text(product['pices'])
            quantity_row = ft.Column(
                [
                    ft.Row(
                        [
                            quantity_label,
                            quantity
                        ]
                    ),
                    ft.Row(
                        [
                            pices_label,
                            pices
                        ]
                    )
                ]
            )
            product_row = ft.Row(
                [
                    image,
                    ft.Column(
                        [
                            name_row,
                            quantity_row
                        ]
                    )
                ]
            )
            self.products_column.controls.append(product_row)
        print(self.products_column.controls)
        self.total_pay.value = f"{self.get_total_pay()} Lei"
        self.total_pay.update()
        self.products_column.update()

        self.buttons_state.value = item['status']
        self.buttons_state.update()
        self.original_status = item['status']
        
    def on_filter_change(self, e):
        print(e.data)
        buffer = []
        if e.data == 'all':
            self.oll_orders_list.controls = self.create_list(self.all_orders, self.on_order_click)
            self.oll_orders_list.update()
        else:
            for order in self.all_orders:
                if order['status'] == e.data:
                    buffer.append(order)
            self.oll_orders_list.controls = self.create_list(buffer, self.on_order_click)
            self.oll_orders_list.update()

    def get_status(self, status):
        STATUS = {
            'on_hold': "In asteptare",
            'new': "Noua",
            'in_progress': "In lucru",
            "completed": "Completa"
        }
        return STATUS[status]
    
    def create_list(self, items, on_click_handler):
        return [
            ft.Container(
                content=ft.Row(
                    [

                        ft.Row(
                            [
                                ft.Icon(ft.Icons.ARROW_RIGHT, size=20),
                                ft.Text(value=item['id'])
                            ]
                        ),
                        ft.Row(
                            [
                                ft.Text(
                                    value=self.get_status(item['status'])
                                )
                            ]
                        )
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                ),
                width=300,
                bgcolor=ft.Colors.BROWN_50,
                padding=10,
                border_radius=8,
                ink=True,
                on_click=lambda e, i=item: on_click_handler(i),
                border = ft.border.all(1, ft.Colors.GREY),
            )
            for item in items
        ]

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    self.header,
                    ft.Row(
                        [
                            ft.Text(value="Filtreaza dupa"),
                            self.fileters
                        ]
                    ),
                    ft.Row(
                        [
                            self.oll_orders_list,
                            self.order_details_placeholder
                        ],
                        vertical_alignment=ft.CrossAxisAlignment.START
                    )
                ],
                alignment=ft.MainAxisAlignment.START,
                expand=True,
                scroll=ft.ScrollMode.ADAPTIVE
            ),
            expand=True,
        )