import flet as ft
from dbActions.providers import Providers as DBProviders

class Providers:
    def __init__(self, page: ft.Page, dashboard, inventory):
        self.page = page
        self.dashboard = dashboard
        self.inventory = inventory
        self.providers_manager = DBProviders()

        self.provider_name = ft.TextField(label="Denumire")
        self.provider_vat = ft.TextField(label="CUI")
        self.provider_register_number = ft.TextField(label="Numar de inregistrare")
        self.provider_address = ft.TextField(label = "Sediu")
        self.contact_name = ft.TextField(label="Nume si prenume")
        self.contact_number = ft.TextField(label="Telefon")
        self.contact_email = ft.TextField(label="E-mail")
        self.add_error_message = ft.Text("",color=ft.Colors.RED)
        self.status = ft.RadioGroup(
            content=ft.Row(
                [
                    ft.Radio(value="Activ", label="Activ"),
                    ft.Radio(value="Inactiv", label="Inactiv"),
                ],
                alignment=ft.MainAxisAlignment.START
            )
        )
        self.status_group = ft.Row(
            [
                ft.Text("Status: ", weight=ft.FontWeight.BOLD),
                self.status
            ]
        )
        

        self.add_dialog = ft.AlertDialog(
            title=ft.Text("Adauga furnizor"),
            content=ft.Column(
                [
                    ft.Text("Furnizor", size=16, weight=ft.FontWeight.BOLD),
                    self.provider_name,
                    self.provider_vat,
                    self.provider_register_number,
                    self.provider_address,
                    ft.Text("Persoana de contact", size=16, weight=ft.FontWeight.BOLD),
                    self.contact_name,
                    self.contact_number,
                    self.contact_email,
                    self.add_error_message
                ],
                width=400,
                height=500
            ),
            actions=[
                ft.FilledButton("Salveaza", on_click=self.on_save_btn_click),
                ft.Button("Cancel", on_click=self.on_cancel_btn_click)
            ]
        )

        self.all_providers = self.providers_manager.get_all_providers()
        self.providers_list = ft.ListView(
            controls=self.create_list(self.all_providers, self.view_provider, self.edit_provider, self.delete_provider),
            spacing=10,
            expand=True
        )

        self.delete_dialog = ft.AlertDialog(
            title=ft.Text("Stergeti furnizorul?"),
            actions = [
                ft.FilledButton("Da", on_click=self.on_delete_btn_click),
                ft.Button("Nu", on_click=self.on_cancel_delete_btn_click)
            ]
        )
        
        self.selected_provider_id = None

        self.search = ft.TextField(label="Cauta", on_submit=self.on_search_btn_click, expand=True)

        self.view_provider_name = ft.Text(value="Denumire")
        self.view_provider_vat = ft.Text(value="CUI")
        self.view_provider_register_number = ft.Text(value="Numar de inregistrare")
        self.view_provider_address = ft.Text(value = "Sediu")
        self.view_contact_name = ft.Text(value="Nume si prenume")
        self.view_contact_number = ft.Text(value="Telefon")
        self.view_contact_email = ft.Text(value="E-mail")
        self.view_created_date = ft.Text(value="Data creare")
        self.view_status = ft.Text(value="Status")

        self.view_dialog = ft.AlertDialog(
            title=self.view_provider_name,
            content=ft.Column(
                [
                    self.view_provider_vat,
                    self.view_provider_register_number,
                    self.view_provider_address,
                    ft.Text(),
                    ft.Text("Persoana de contact", weight=ft.FontWeight.BOLD),
                    self.view_contact_name,
                    self.view_contact_number,
                    self.view_contact_email,
                    ft.Text(),
                    self.view_created_date,
                    self.view_status
                ],
                width=400,
                height=300
            ),
            actions=[ft.Button("Close", on_click=self.on_close_btn_click)]
        )

        self.is_editing = None
    
    def on_delete_btn_click(self, e):
        self.providers_manager.remove_provider(self.selected_provider_id)
        self.selected_provider_id = None
        self.page.close(self.delete_dialog)
        
        self.all_providers = self.providers_manager.get_all_providers()
        self.providers_list.controls=self.create_list(self.all_providers, self.view_provider, self.edit_provider, self.delete_provider)
        self.providers_list.update()

    def on_cancel_delete_btn_click(self, e):
        self.selected_provider_id = None
        self.page.close(self.delete_dialog)

    def view_provider(self, item):
        self.view_provider_name.value = item['provider_name']
        self.view_provider_vat.value = 'CUI: ' + item['provider_vat']
        self.view_provider_register_number.value = "Numar de inregistrare: "+item['provider_register_number']
        self.view_provider_address.value = "Sediu: " + item['provider_address']
        self.view_contact_name.value = "Nume si prenume: " + item['contact_name']
        self.view_contact_number.value = "Telefon: " + item['contact_number']
        self.view_contact_email.value = "E-mail: " + item['contact_email']
        self.view_created_date.value = "Creat la: " + item['created_at']
        self.view_status.value = "Status: " + item['status']
        self.page.open(self.view_dialog)

    def on_close_btn_click(self, e):
        self.page.close(self.view_dialog)


    def delete_provider(self, id):
        print("Delete ", id)
        self.selected_provider_id = id
        self.page.open(self.delete_dialog)
        
    def on_search_btn_click(self, e):
        search = self.search.value
        buffer = []
        for provider in self.all_providers:
            if search.lower() in provider['provider_name'].lower():
                buffer.append(provider)

        self.providers_list.controls=self.create_list(buffer, self.view_provider, self.edit_provider, self.delete_provider)
        self.providers_list.update()
        

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

                        ft.Row(
                            [
                                ft.Icon(name=ft.Icons.FIRE_TRUCK, size=40),
                                ft.Column(
                                    [
                                        ft.Text(value=f"Denumire: {item['provider_name']}", weight=ft.FontWeight.BOLD),
                                        ft.Text(value=f"Status: {item['status']}", size=12)
                                    ]
                                )
                            ]
                        ),
             
                        ft.Row(
                            [
                                ft.IconButton(
                                    icon=ft.Icons.PREVIEW,
                                    on_click=lambda e, id=item: on_click_handler(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,
                ),
                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_add_btn_click(self, e):
        self.page.open(self.add_dialog)

    def on_save_btn_click(self, e):
        self.page.close(self.add_dialog)
        provider = {
            'provider_name':self.provider_name.value,
            'provider_vat':self.provider_vat.value,
            'provider_register_number':self.provider_register_number.value,
            'provider_address':self.provider_address.value,
            'contact_name':self.contact_name.value,
            'contact_number':self.contact_number.value,
            'contact_email':self.contact_email.value,
            'add_error_message':self.add_error_message.value
        }
        if not self.is_editing:
            print('Add provider: ', provider)
            self.providers_manager.add_provider(provider)
        else:
            provider['id'] = self.is_editing
            provider['status'] = self.status.value
            print('Edit provider: ', provider)
            self.providers_manager.update_provider(provider)
            self.is_editing = None

        self.all_providers = self.providers_manager.get_all_providers()
        self.providers_list.controls=self.create_list(self.all_providers, self.view_provider, self.edit_provider, self.delete_provider)
        self.providers_list.update()

        self.reset_fields()

        

    def on_cancel_btn_click(self, e):
        self.page.close(self.add_dialog)
        self.reset_fields()

    def reset_fields(self):
        self.provider_name.value = None
        self.provider_name.update()
        self.provider_vat.value = None
        self.provider_vat.update()
        self.provider_register_number.value = None
        self.provider_register_number.update()
        self.provider_address.value = None
        self.provider_address.update()
        self.contact_name.value = None
        self.contact_name.update()
        self.contact_number.value = None
        self.contact_number.update()
        self.contact_email.value = None
        self.contact_email.update()
        self.add_error_message.value = None
        self.add_error_message.update()
        try:
            self.add_dialog.content.controls.remove(self.status)
        except:
            pass
        self.add_dialog.content.height = 500

    def edit_provider(self, item):
        self.is_editing = item['id']
        self.provider_name.value = item['provider_name']
        self.provider_vat.value = item['provider_vat']
        self.provider_register_number.value = item['provider_register_number']
        self.provider_address.value = item['provider_address']
        self.contact_name.value = item['contact_name']
        self.contact_number.value = item['contact_number']
        self.contact_email.value = item['contact_email']
        self.status.value = item['status']
        self.add_dialog.content.controls.append(self.status_group)
        self.add_dialog.content.height = 600
        self.page.open(self.add_dialog)

    def build(self):
        return ft.Container(
            ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Furnizori", 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
                    ),
                    ft.Row(
                        [
                            self.search, 
                            ft.IconButton(icon=ft.Icons.SEARCH, on_click=self.on_search_btn_click)
                        ]
                    ),
                    self.providers_list
                ]
            )
        )