import flet as ft
from dbActions.products import Products
from dbActions.categories import Categories
from admin.products import ProductsPage
from dbActions.packing_products import PackingProducts

class Packing:
    def __init__(self, page: ft.Page, dashboard, inventory):
        self.page = page
        self.dashboard = dashboard
        self.inventory = inventory

        self.product_id = None
        self.products_manager = Products()
        self.category_manager = Categories()
        self.products_page = ProductsPage(self.page)
        self.packing_product_manager = PackingProducts()
        self.all_products = self.products_manager.get_all()
        self.categories = self.category_manager.get_categories()
        self.list_products = ft.ListView(
            controls=self.create_list(self.all_products, self.on_products_btn_click),
            expand=True,
            spacing=10,
            width=350,
            height=450
        )
        self.name = ft.TextField(label="Denumire", read_only=True, disabled=True)
        self.category = ft.TextField(label="Categorie", read_only=True, disabled=True)
        self.quantity = ft.TextField(label="Grame/buc", read_only=True, disabled=True)
        self.init_stock = ft.TextField(label = "Stoc initial", read_only=True, disabled=True)
        self.masure = ft.TextField(label="Unitate de masura", value="BUC", read_only=True, disabled=True)
        self.new_stock = ft.TextField(label="Stoc nou")
        self.enter_price = ft.TextField(label="Pret intrare")
        self.exit_price = ft.TextField(label = "Pret vanzare", read_only=True, disabled=True)
        self.stock_min = ft.TextField(label = "Stoc minim")
        self.stock_max = ft.TextField(label = "Stoc maxim")

        self.search_bar = ft.TextField(label="Cauta", on_submit=self.on_search_btn_click)
        self.search_btn = ft.IconButton(
            icon=ft.Icons.SEARCH, 
            on_click=self.on_search_btn_click, 
            bgcolor=ft.Colors.BROWN,
            icon_color=ft.Colors.WHITE
        )

        self.add_new_item_dialog = ft.AlertDialog(
            title=ft.Text("Adauga intrare noua"),
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Column(
                                [     
                                    ft.Row(
                                        [
                                            self.search_bar,
                                            self.search_btn
                                        ],
                                    ),
                                    self.list_products,
                                    ft.Button(
                                        "Adauga produs", 
                                        on_click=self.on_add_produt_btn_click,
                                        icon=ft.Icons.ADD,
                                        width=350
                                    ),

                                ],
                                width=350
                            ),
                            ft.VerticalDivider(width=2) ,
                            ft.Column(
                                [
                                    self.name,
                                    self.category,
                                    self.quantity,
                                    self.init_stock,
                                    self.new_stock,
                                    self.masure,
                                    self.enter_price,
                                    self.exit_price,
                                    self.stock_min,
                                    self.stock_max
                                ],
                                width=320,
                                height=550,
                                scroll=ft.ScrollMode.AUTO
                            )
                        ],
                        vertical_alignment=ft.CrossAxisAlignment.START,
                        spacing=10
                    )
                ],
                width=700,
                height=650,
                alignment=ft.MainAxisAlignment.START
            ),
            actions=[
                ft.FilledButton("Salveaza", on_click=self.on_save_btn_click),
                ft.Button("Anuleaza", on_click=self.on_cancel_btn_click)
            ]
        )

        self.selected_product_id = None

        self.all_packed_products = self.packing_product_manager.get_all()
        self.data_table = ft.DataTable(
            columns=[
                ft.DataColumn(label=ft.Text("Denumire")),
                ft.DataColumn(label=ft.Text("Categorie")),
                ft.DataColumn(label=ft.Text("Gramaj / Buc")),
                ft.DataColumn(label=ft.Text("Stoc")),
                ft.DataColumn(label=ft.Text("Unitatea de masura")),
                ft.DataColumn(label=ft.Text("Pret intrare")),
                ft.DataColumn(label=ft.Text("Pret vanzare")),
                ft.DataColumn(label=ft.Text("Stoc minim")),
                ft.DataColumn(label=ft.Text("Stoc maxim"))
            ],
            rows=[],
            expand=True
        )
        for pack_product in self.all_packed_products:
            for product in self.all_products:
                if pack_product['product_id'] == product['id']:
                    categorie = self.get_category_name(product['category_id'])
                    print(categorie)
                    row = ft.DataRow(
                            cells=[
                                ft.DataCell(ft.Text(product['name'])),
                                ft.DataCell(ft.Text(categorie)),
                                ft.DataCell(ft.Text(product['quantity'])),
                                ft.DataCell(ft.Text(pack_product['stock'])),
                                ft.DataCell(ft.Text("BUC")),
                                ft.DataCell(ft.Text(pack_product['enter_price'])),
                                ft.DataCell(ft.Text(product['price'])),
                                ft.DataCell(ft.Text(pack_product['stock_min'])),
                                ft.DataCell(ft.Text(pack_product['stock_max']))
                            ],
                        )
                    self.data_table.rows.append(row)

    def on_add_produt_btn_click(self, e):
        self.page.close(self.add_new_item_dialog)
        self.dashboard.placeholder.content = self.products_page.build()
        self.dashboard.placeholder.update()

    def on_save_btn_click(self, e):
        product_id = self.selected_product_id
        init_stock = self.init_stock.value
        new_stock = self.new_stock.value 
        stock = 0
        try:
            stock = int(init_stock) + int(new_stock)
        except Exception as e:
            print(e)
            return
        enter_price = self.enter_price.value
        stock_min = self.stock_min.value
        stock_max = self.stock_max.value
        self.page.close(self.add_new_item_dialog)
        self.product_data = self.packing_product_manager.get_packing_product_by_product_id(product_id)
        if self.product_data:
            self.packing_product_manager.update_packing_products(
                id = self.product_data['id'],
                product_id = product_id,
                stock = stock,
                enter_price=enter_price,
                stock_min=stock_min,
                stock_max=stock_max
            )
        else:
            self.packing_product_manager.add_packing_product(
                product_id = product_id,
                stock = stock,
                enter_price=enter_price,
                stock_min=stock_min,
                stock_max=stock_max
            )
        self.selected_product_id = None

        self.reset_filed()

    def on_cancel_btn_click(self, e):
        print("cancel dialog")
        self.page.close(self.add_new_item_dialog)

    def on_search_btn_click(self, e):
        buffer = []
        search = self.search_bar.value
        for product in self.all_products:
            if search.lower() in product['name'].lower():
                buffer.append(product)
        self.list_products.controls = self.create_list(buffer, self.on_products_btn_click)
        self.list_products.update()
    
    def get_total(self,  update = False):
        try:
            print("calculating total")
            init = float(self.init_stock.value) if self.init_stock.value else 0
            new = float(self.new_stock.value) if self.new_stock.value else 0
            return init + new
        except Exception as e:
            print(e)
    
    def on_products_btn_click(self, item):
        #product data
        self.product_data = self.packing_product_manager.get_packing_product_by_product_id(item['id'])
        print(self.product_data)
        self.selected_product_id = item['id']

        self.name.value = item['name']
        self.name.update()
        self.category.value = self.get_category_name(item['category_id'])
        self.category.update()
        self.quantity.value = item['quantity']
        self.quantity.update()
        self.exit_price.value = item['price']
        self.exit_price.update()
        #new order data
        self.init_stock.value = self.product_data['stock'] if self.product_data else '0'
        self.init_stock.update()
        self.new_stock.value = ''
        self.new_stock.update()
        self.enter_price.value = self.product_data['enter_price'] if self.product_data else ''
        self.enter_price.update()
        self.stock_min.value = self.product_data['stock_min'] if self.product_data else ''
        self.stock_min.update()
        self.stock_max.value = self.product_data['stock_max'] if self.product_data else ''  
        self.stock_max.update()

    def reset_filed(self):
        self.name.value = None
        self.name.update()
        self.category.value = None
        self.category.update()
        self.quantity.value = None
        self.quantity.update()
        self.exit_price.value = None
        self.exit_price.update()
        self.init_stock.value = None
        self.init_stock.update()
        self.new_stock.value = None
        self.new_stock.update()
        self.enter_price.value = None
        self.enter_price.update()
        self.stock_min.value = None
        self.stock_min.update()
        self.stock_max.value = None
        self.stock_max.update()

    def get_category_name(self, id):
        for category in self.categories:
            if int(category['id']) == int(id):
                return category['name']

    def create_list(self, items, on_click_handler):
        """Helper to create list items for a column."""
        return [
            ft.Container(
                content=ft.Row(
                    [
                        ft.Row(
                            [
                                ft.Image(
                                    src=item['image'], 
                                    width=50, 
                                    height=50, 
                                    fit=ft.ImageFit.COVER,
                                    border_radius=5
                                ),
                                ft.Column(
                                    [
                                        ft.Text(value=item['name'], weight=ft.FontWeight.BOLD, size=15),
                                        ft.Text(value=f"Categorie: {self.get_category_name(item['category_id'])}", size=12)
                                    ]
                                ),
                            ]
                        )
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                ),
                width=300,
                bgcolor=ft.Colors.BROWN_50,
                padding=10,
                border_radius=8,
                border = ft.border.all(1, ft.Colors.GREY),
                ink=True,
                on_click=lambda e, id=item: on_click_handler(id)
            )
            for item in items
        ]

    def on_add_btn_click(self, e):
        self.page.open(self.add_new_item_dialog)

    def build(self):
        return ft.Container(
            ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Ambalare Produse", weight=ft.FontWeight.BOLD, size=18),
                            ft.Button("Adauga", icon=ft.Icons.ADD, on_click=self.on_add_btn_click)
                        ],
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                    ),
                    self.data_table
                ]
            )
        )