import flet as ft
from dbActions.categories import Categories
from dbActions.products import Products

class Home:
    def __init__(self, page: ft.Page):
        self.page = page
        self.categories_manager = Categories()
        self.header = ft.Row(
            [
                #ft.Button("Acasa", icon=ft.Icons.HOME, on_click=self.on_acasa_btn_click)
                ft.Text("Categori", weight=ft.FontWeight.BOLD, size=18)
            ], 
            alignment=ft.MainAxisAlignment.CENTER,
            width=1000
        )
        self.banner = ft.Image("images/banner.png", width=1000, height=350, fit=ft.ImageFit.COVER)
        self.categories_group = ft.Row([], scroll=ft.ScrollMode.ADAPTIVE, expand=True)
        self.add_categories()
        self.products_manager = Products()
        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()[:20]
        self.add_products(self.products)

        self.searchbar = ft.TextField(
            label="Cauta produsul in toate categoriile", 
            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)
        self.search_for = self.page.session.get("search_for")
        if self.search_for:
            self.searchbar.value = self.page.session.get("search_for")
            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.page.session.set("search_for", None)
            self.searchbar.value = ''

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

    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"{round(float(product['price']) - float(product['price'])*float(product['discount'])/100,2)}", 
                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 add_categories(self):
        categories = self.categories_manager.get_categories()
        for category in categories:
            card = ft.Card(
                content=ft.Container(
                    content=ft.Column(
                        [
                            ft.Image(
                                src=category['image'], 
                                width=100, 
                                height = 80, 
                                border_radius=10,
                                fit=ft.ImageFit.COVER),
                            ft.Text(category['name'])
                        ],
                        horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                    ),
                    ink=True,
                    on_click=lambda e, title=category: self.on_category_click(title),
                    padding=5,
                    width=120, 
                    height=120
                )
            )
            self.categories_group.controls.append(card)

    def on_category_click(self, cat):
        name = cat['name'].replace(" ","-").lower()
        self.page.session.set("category", cat)
        self.page.go(f"/categorie/{name}")

    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_profile_btn_click(self, e):
        self.page.go('/profil')

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

    def on_search_btn_click(self, e):
        search = self.searchbar.value
        buffer = []
        for product in self.products_manager.get_all():
            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_about_us_btn_click(self, e):
        self.page.go('/about_us')

    def on_terms_and_cond_btn_click(self, e):
        self.page.go("/termeni_si_conditii")

    def on_cancel_policy_btn_click(self, e):
        self.page.go("/politica_de_anulare_comanda")

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

    def on_delivery_policy_btn_click(self, e):
        self.page.go("/politica_de_livrare_comanda")

    def on_gdpr_btn_click(self, e):
        self.page.go("/gdpr")

    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
                    ),
                    self.banner,
                    ft.Column(
                        [  
                            self.header,
                            self.categories_group,
                            ft.Row(
                                [
                                    ft.Text("Produse Populare", size=18, weight=ft.FontWeight.BOLD),
                                ], 
                                alignment=ft.MainAxisAlignment.CENTER,
                                width=1000
                            ),
                            self.products_group,
                            ft.Divider(height=1),
                            ft.Row(
                                [
                                    ft.Column(
                                        [
                                            ft.TextButton("Despre noi", on_click=self.on_about_us_btn_click, icon=ft.Icons.INFO),
                                            ft.TextButton("Termeni si conditii", on_click=self.on_terms_and_cond_btn_click, icon=ft.Icons.INFO),
                                            ft.TextButton("Politica de anulare comanda",on_click=self.on_cancel_policy_btn_click, icon=ft.Icons.INFO),
                                            ft.TextButton("Politica de confidentialitate",on_click=self.on_confidentiality_policy_btn_click, icon=ft.Icons.INFO),
                                            ft.TextButton("Politica de livrare comanda",on_click=self.on_delivery_policy_btn_click, icon=ft.Icons.INFO),
                                            ft.TextButton("Politica GDPR (siguranța datelor cu caracter personal)",on_click=self.on_gdpr_btn_click, icon=ft.Icons.INFO)
                                        ]
                                    ),
                                    ft.Column(
                                        [
                                            ft.TextButton("TainaGustului", icon=ft.Icons.FACEBOOK)
                                        ]
                                    )
                                ],
                                alignment=ft.MainAxisAlignment.SPACE_AROUND,
                                vertical_alignment=ft.CrossAxisAlignment.START
                            )
                        ],
                        horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                        expand=True,
                        width=1000
                    )
                ],
                scroll=ft.ScrollMode.ADAPTIVE,
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
            ),
            expand=True,
            padding=10,
            bgcolor=ft.Colors.WHITE
        )