import flet as ft
from dbActions.provider_bills import ProviderBills
from dbActions.providers import Providers
from dbActions.bulk_products import BulkProducts

class GoodsReception:
    def __init__(self, page: ft.Page, dashboard, inventory):
        self.page = page
        self.bill_manager = ProviderBills()
        self.provider_manager = Providers()
        self.bulk_products_manager = BulkProducts()

        self.product_suggestions = ft.Text(size=12)
        self.product_name = ft.TextField(label="Denumire", on_change=self.search_for_product_name)
        self.product_mesure_unit = ft.Dropdown(
            label="Unitate de masura",
                options=[
                ft.dropdown.Option(key='kg', text="KG"),
                ft.dropdown.Option(key='buc', text="BUC")
            ] ,
            expand=True
        )
        self.product_mesure_unit.value = 'kg'
        self.product_quantity = ft.TextField(label="Cantitate (Numar de unitati)")
        self.product_price = ft.TextField(label="Pret pe unitate")
        self.product_vat = ft.TextField(label="TVA% (0 pentru neplatitor de TVA)", value="0")

        self.bill_number = ft.TextField(label="Serie si numar")
        self.bill_date = ft.TextField(label="Data", read_only=True, expand=True)
        self.provider = ft.Dropdown(
            label="Furnizor",
            options=self.get_providers(),
            expand=True
        )

        self.add_bill_dialog = ft.AlertDialog(
            title=ft.Text("Adauga factura"),
            content=ft.Column(
                [
                    self.bill_number,
                    ft.Row(
                        [
                            self.bill_date,
                            ft.ElevatedButton(
                                "Selecteaza",
                                icon=ft.Icons.CALENDAR_MONTH,
                                on_click=lambda e: page.open(
                                    ft.DatePicker(
                                        on_change=self.on_date_selected,
                                    )
                                ),
                            )
                        ],
                        width=400
                    ),
                    self.provider
                ],
                width=400,
                height=200
            ),
            actions=[
                ft.Button(
                    "Salveaza", 
                    on_click=self.on_save_bill_btn_click,
                    icon=ft.Icons.SAVE
                ),
                ft.Button(
                    "Anuleaza", 
                    on_click=self.on_cancel_bill_btn_click,
                    icon=ft.Icons.CANCEL,
                    bgcolor=ft.Colors.GREY,
                    color=ft.Colors.WHITE
                )
            ]
        )

        self.all_bills = self.bill_manager.get_all()

        self.bills_list = ft.ListView(
            controls=self.create_bill_list(
                self.all_bills, 
                self.on_add_product_btn_click,
                self.on_edit_provider_bill_btn_click,
                self.on_delete_provider_bill_btn_click,
                self.on_view_list_btn_click
            ),
            spacing=10,
            expand=True,
            width=400
        )

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

        self.delete_item_id = None

        self.delete_bill_dialog = ft.AlertDialog(
            title=ft.Text("Setergeti?"),
            actions=[
                ft.Button("Da", on_click=self.on_confirm_delete_bill_btn_click),
                ft.Button("Nu", on_click=self.on_cancel_delete_bill_btn_click, bgcolor=ft.Colors.GREY, color=ft.Colors.WHITE)
            ]
        )

        self.edit_item = None

        self.add_product_dialog = ft.AlertDialog(
            title=ft.Text("Adauga produs"),
            content=ft.Column(
                [
                    self.product_suggestions,
                    self.product_name, 
                    self.product_quantity,
                    self.product_mesure_unit,
                    self.product_price,
                    self.product_vat
                ],
                width=400,
                height=300
            ),
            actions=[
                ft.Button(
                    "Salveaza", 
                    icon=ft.Icons.SAVE,
                    on_click=self.on_save_product_btn_click
                ),
                ft.TextButton(
                    "Anuleaza",
                    on_click=self.on_cancel_product_btn_click
                )
            ]
        )

        self.selected_bill = None

        self.products_table = ft.DataTable(
            columns=[
                ft.DataColumn(ft.Text("Produs", weight=ft.FontWeight.BOLD)),
                ft.DataColumn(ft.Text("Cantitate", weight=ft.FontWeight.BOLD)),
                ft.DataColumn(ft.Text("Unitate\nde masura", weight=ft.FontWeight.BOLD)),
                ft.DataColumn(ft.Text("Pret\nfara TVA", weight=ft.FontWeight.BOLD)),
                ft.DataColumn(ft.Text("Procent\nTVA(%)", weight=ft.FontWeight.BOLD)),
                ft.DataColumn(ft.Text("Pret\nproduse", weight=ft.FontWeight.BOLD)),
                ft.DataColumn(ft.Text("Valoare\nTVA", weight=ft.FontWeight.BOLD)),
                ft.DataColumn(ft.Text("Pret\nfinal", weight=ft.FontWeight.BOLD)),
            ],
            rows=[]
        )

        self.total = ft.Text("", weight=ft.FontWeight.BOLD)
        self.placeholder = ft.Column([self.products_table, self.total], width=900, scroll=ft.ScrollMode.ADAPTIVE, height=600)
        self.all_procuts = None    

    def set_total(self):
        tl = 0
        all_products = self.bulk_products_manager.get_products_by_bill_id(self.selected_bill['id'])
        for product in all_products:
            tl += (product['price']*product['quantity'])*product['vat']/100+(product['price']*product['quantity'])
        self.total.value = f'Total: {round(tl,2)}'
        self.total.update()

    def search_for_product_name(self, e):
        produts_names = []
        for product in self.all_procuts:
            if len(self.product_name.value) >= 4:
                if self.product_name.value in product['name']:
                    print('Suggested name', product['name'])
                    produts_names.append(product['name'])
        self.product_suggestions.value = produts_names
        self.product_suggestions.update()

    def show_bill_products(self):
        all_products = self.bulk_products_manager.get_products_by_bill_id(self.selected_bill['id'])
        print(all_products)
        self.products_table.rows.clear()
        for product in all_products:
            print(product)
            price = round((product['price']*product['quantity'])*product['vat']/100+(product['price']*product['quantity']),2)
            product_price = round(product['price']*product['quantity'],2)
            vat_value = round((product['price']*product['quantity'])*product['vat']/100,2)
            self.products_table.rows.append(
                ft.DataRow(
                    cells=[
                        ft.DataCell(ft.Text(product['name'])),
                        ft.DataCell(ft.Text(product['quantity'])),
                        ft.DataCell(ft.Text(product['mesure_unit'])),
                        ft.DataCell(ft.Text(product['price'])),
                        ft.DataCell(ft.Text(product['vat'])),
                        ft.DataCell(ft.Text(product_price)),
                        ft.DataCell(ft.Text(vat_value)),
                        ft.DataCell(ft.Text(price)),
                    ],
                )
            )
            self.products_table.update()

    def on_save_product_btn_click(self, e):
        name = self.product_name.value 
        quantity = self.product_quantity.value
        mesure_unit = self.product_mesure_unit.value
        price = self.product_price.value
        vat = self.product_vat.value
        self.bulk_products_manager.add_bulk_products_product(
            bill_id=self.selected_bill['id'],
            name=name,
            mesure_unit=mesure_unit,
            quantity=quantity,
            price=price,
            vat=vat
        )
        self.reset_values()
        self.page.close(self.add_product_dialog)
        self.show_bill_products()
        self.set_total()

    def on_cancel_product_btn_click(self, e):
        self.reset_values()
        self.page.close(self.add_product_dialog)

    def reset_values(self):
        self.product_name.value = ''
        self.product_name.update()
        self.product_quantity.value = ''
        self.product_quantity.update()
        self.product_mesure_unit.value = 'kg'
        self.product_mesure_unit.update()
        self.product_price.value = ''
        self.product_price.update()
        self.product_vat.value = '0'
        self.product_vat.update()
        

    def on_confirm_delete_bill_btn_click(self, e):
        self.page.close(self.delete_bill_dialog)
        self.bill_manager.remove(self.delete_item_id)
        self.delete_item_id = None
        list_value = self.bill_manager.get_all()
        self.update_list(list_value)

    def on_cancel_delete_bill_btn_click(self, e):
        self.page.close(self.delete_bill_dialog)
        self.delete_item_id = None

    def on_add_product_btn_click(self, item):
        self.selected_bill = item
        self.all_procuts = self.bulk_products_manager.get_all()
        self.page.open(self.add_product_dialog)

    def on_view_list_btn_click(self, item):
        self.selected_bill = item
        self.show_bill_products()
        self.set_total()

    def on_edit_provider_bill_btn_click(self, item):
        self.edit_item = item
        self.bill_number.value = item['number']
        self.bill_date.value = item['date']
        self.provider.value = item['provider_id']
        self.page.open(self.add_bill_dialog)

    def on_delete_provider_bill_btn_click(self, id):
        print("Delete ", id)
        self.delete_item_id = id
        self.page.open(self.delete_bill_dialog)

    def get_provider_name(self, id):
        for provider in self.provider_manager.get_all_providers():
            if provider['id'] == id:
                return provider['provider_name']

    def create_bill_list(self, items, on_click_handler, on_click_handler2, on_click_handler3, on_click_handler4):
        """Helper to create list items for a column."""
        return [
            ft.Container(
                content=ft.Row(
                    [

                        ft.Column(
                            [
                                ft.Text(value=f"Factura: {item['number']} {item['date']}", weight=ft.FontWeight.BOLD),
                                ft.Text(value=f"Din: {item['date']}", size=12),
                                ft.Text(value=f"Furnizor: {self.get_provider_name(item['provider_id'])}", size=12)
                            ]
                        ),
             
                        ft.Column(
                            [
                                ft.FilledButton(
                                    icon=ft.Icons.ADD,
                                    text = 'Adauga Produs',
                                    on_click=lambda e, id=item: on_click_handler(id),
                                ),
                                ft.Row(
                                    [
                                        ft.IconButton(
                                            icon=ft.Icons.PREVIEW,
                                            on_click=lambda e, id=item: on_click_handler4(id)
                                        ),
                                        ft.IconButton(
                                            icon=ft.Icons.EDIT,
                                            on_click=lambda e, id=item: on_click_handler2(id),
                                        ),
                                        ft.IconButton(
                                            icon=ft.Icons.DELETE,
                                            on_click=lambda e, id=item['id']: on_click_handler3(id), 
                                            icon_color=ft.Colors.RED,
                                        )
                                    ],
                                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                                    expand=True
                                )
                            ]
                        )
                        
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                    vertical_alignment=ft.CrossAxisAlignment.END
                ),
                width=300,
                bgcolor=ft.Colors.BROWN_50,
                border = ft.border.all(1, ft.Colors.GREY),
                padding=10,
                border_radius=8,
            )
            for item in items
        ]

    def on_date_selected(self, e):
        self.bill_date.value = e.control.value.strftime('%d/%m/%Y')
        self.bill_date.update()

    def on_add_bill_btn_click(self, e):
        self.page.open(self.add_bill_dialog)

    def get_providers(self):
        providers = self.provider_manager.get_all_providers()
        return [
            ft.dropdown.Option(key=provider['id'], text=provider['provider_name'])
            for provider in providers
        ] 
    
    def on_save_bill_btn_click(self, e):
        if self.bill_number.value == None or len(self.bill_number.value)<2:
            print("bill number not inserted")
            return
        if self.edit_item:
            print("Edit bill")
            self.bill_manager.update(
                id=self.edit_item['id'],
                number=self.bill_number.value,
                date=self.bill_date.value,
                provider_id=self.provider.value
            )
            self.edit_item = None
        else:
            print('Add bill')
            self.bill_manager.add_provider_bills(
                self.bill_number.value,
                self.bill_date.value,
                self.provider.value
            )
        self.on_cancel_bill_btn_click('e')
        list_value = self.bill_manager.get_all()
        self.update_list(list_value)

    def on_cancel_bill_btn_click(self, e):
        self.bill_number.value = ''
        self.bill_number.update()
        self.bill_date.value = ''
        self.bill_date.update()
        self.provider.value = ''
        self.provider.update()
        self.page.close(self.add_bill_dialog)

    def on_search_btn_click(self, e):
        search = self.search_bar.value
        buffer = []
        for bill in self.all_bills:
            if search.lower() in bill['number'].lower():
                buffer.append(bill)
        self.update_list(buffer)
    
    def update_list(self, list_value):
        self.bills_list.controls=self.create_bill_list(
            list_value, 
            self.on_add_product_btn_click,
            self.on_edit_provider_bill_btn_click,
            self.on_delete_provider_bill_btn_click,
            self.on_view_list_btn_click
        )
        self.bills_list.update()

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Receptie Marfa", weight=ft.FontWeight.BOLD, size=18),
                            ft.Button("Adauga Factura", icon=ft.Icons.ADD, on_click=self.on_add_bill_btn_click)
                        ],
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                        vertical_alignment=ft.CrossAxisAlignment.START
                    ),
                    ft.Row(
                        [
                            self.search_bar,
                            self.search_btn
                        ],
                        vertical_alignment=ft.CrossAxisAlignment.START
                    ),
                    ft.Row(
                        [
                            self.bills_list,
                            self.placeholder
                        ],
                        vertical_alignment=ft.CrossAxisAlignment.START
                    ) 
                ],
                alignment=ft.MainAxisAlignment.START,
                expand=True
            ),
            expand=True
        )