import flet as ft
from dbActions.products import Products

class Category:
    def __init__(self, page: ft.Page):
        self.page = page
        self.products_manager = Products()
        self.category = self.page.session.get("category")

        self.products_group = ft.GridView(
            spacing=10,
            runs_count=5,
            max_extent=200,
            child_aspect_ratio=1.0,
            expand=True,
            width=1000
        )
        self.products = self.products_manager.get_all_by_category(self.category['id'])
        self.add_products(self.products)
        self.searchbar = ft.TextField(
            label="Cauta produsul aceasta categorie", 
            expand=True,
            on_submit=self.on_search_btn_click
        )

        self.profile_placeholder = ft.Column()
        self.profile_btn = ft.IconButton(
            icon=ft.Icons.ACCOUNT_CIRCLE_OUTLINED,
            on_click=self.on_profile_btn_click,
            bgcolor=ft.Colors.BROWN,
            icon_color=ft.Colors.WHITE
        )
        self.login_btn = ft.IconButton(
            icon=ft.Icons.LOGIN,
            on_click=self.on_login_btn_click,
            bgcolor=ft.Colors.BROWN,
            icon_color=ft.Colors.WHITE
        )
        if self.page.session.get("user") is not None and '@default.com' not in self.page.session.get("user")['email']:
            self.profile_placeholder.controls.append(self.profile_btn)
        else:
            self.profile_placeholder.controls.append(self.login_btn)
    
    def on_login_btn_click(self, e):
        self.page.go('/auth')

    def add_products(self, products):
        for product in products:
            self.new_price = ft.Text(
                value=f"{float(product['price']) - float(product['price'])*float(product['discount'])/100}", 
                size=14 if product['discount'] != 0 else 12, 
                color=ft.Colors.RED  if product['discount'] != 0 else  ft.Colors.BLACK, 
                weight=ft.FontWeight.BOLD
            )
            print(type(product['discount']))
            self.old_price = ft.Text(
                value=f"{product['price']}" if product['discount'] != 0 else '', 
                size=12, 
                color=ft.Colors.GREY, 
                style=ft.TextStyle(decoration=ft.TextDecoration.LINE_THROUGH),
            )
            card = ft.Card(
                content=ft.Container(
                    content=ft.Column(
                        [
                            ft.Image(src=product['image'], width=170, height=100, border_radius=10, fit=ft.ImageFit.COVER),
                            ft.Text(product['name'], weight=ft.FontWeight.BOLD),
                            ft.Row(
                                [
                                    ft.Text(f"Pret:", size=12),
                                    self.old_price,
                                    self.new_price,
                                    ft.Text(f"lei/{product['quantity']}g", size=12),
                                ],
                                alignment=ft.MainAxisAlignment.CENTER,
                                spacing=4
                            )
                        ],
                        horizontal_alignment=ft.CrossAxisAlignment.CENTER
                    ),
                    ink=True,
                    on_click=lambda e, title=product: self.on_product_click(title),
                    padding=5
                )
            )
            self.products_group.controls.append(card)

    def on_search_btn_click(self, e):
        search = self.searchbar.value
        buffer = []
        for product in self.products:
            if search.lower() in product['name'].lower():
                buffer.append(product)
        self.products_group.controls.clear()
        self.add_products(buffer)
        self.products_group.update()
        self.searchbar.value = ''
        self.searchbar.update()

    def on_profile_btn_click(self, e):
        self.page.go('/profil')

    def on_home_btn_click(self, e):
        self.page.go('/')

    def on_product_click(self, product):
        self.page.session.set("product", product)
        name = product['name'].replace(" ", "-").lower()
        self.page.go(f'/produs/{name}')

    def on_cart_btn_click(self, e):
        self.page.go("/pre_load_cos")

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            self.searchbar,
                            ft.IconButton(
                                icon=ft.Icons.SEARCH, 
                                on_click=self.on_search_btn_click,
                                bgcolor=ft.Colors.BROWN,
                                icon_color=ft.Colors.WHITE
                            ),
                            ft.VerticalDivider(), 
                            self.profile_placeholder,
                            ft.IconButton(
                                icon=ft.Icons.SHOPPING_CART_OUTLINED,
                                bgcolor=ft.Colors.BROWN,
                                icon_color=ft.Colors.WHITE,
                                on_click=self.on_cart_btn_click
                            )
                        ],
                        width=1000
                    ),
                    ft.Row(
                        [
                            ft.IconButton(icon=ft.Icons.HOME, on_click=self.on_home_btn_click),
                            ft.Text(
                                value=self.category['name'], 
                                weight=ft.FontWeight.BOLD, 
                                size=18
                            ),
                        ],
                        width=1000
                    ),
                    self.products_group
                ],
                scroll=ft.ScrollMode.ADAPTIVE,
                expand=True,
                horizontal_alignment=ft.CrossAxisAlignment.CENTER
            ),
            expand=True,
            padding=10,
            bgcolor=ft.Colors.WHITE
        )