import flet as ft
from dbActions.users import Users
from dbActions.company import Company

class Clients:
    def __init__(self, page: ft.Page):
        self.page = page
        self.user_manager = Users()
        self.company_manager = Company()
 
        self.first_name = ft.TextField(label="Prenume")
        self.last_name = ft.TextField(label="Nume")
        self.email = ft.TextField(label="E-mail")
        self.phone = ft.TextField(label="Telefon")
        self.address = ft.TextField(
            label="Strada si numar", 
            multiline=True, 
            min_lines=3, 
            max_lines=5
        )
        self.city = ft.TextField(
            label="Oras"
        )
        self.company_name = ft.TextField(label="Denumire firma")
        self.vat = ft.TextField(label="CUI")
        self.register_number = ft.TextField(label="Numar registru comert")
        self.company_address = ft.TextField(label="Sediu",  multiline=True, min_lines=3, max_lines=5)
        self.company_placeholder = ft.Column()
        self.second_address_placeholder = ft.Column()
        self.second_address = ft.TextField(
                label="Adresa de livrare",
                multiline=True, 
                min_lines=3, 
                max_lines=5
            )

        self.client_column = ft.Column(
            [
                self.first_name,
                self.last_name,
                self.email,
                self.phone,
                self.address,
                self.city,
                ft.Button("Persoana Juridica?", on_click=self.on_is_comopany_btn_click),
                self.company_placeholder,
                ft.Button("Adresa de livrare difera de adresa de domiciliu?", on_click=self.on_second_address),
                self.second_address_placeholder
            ],
            scroll=ft.ScrollMode.ADAPTIVE,
            width=400,
            auto_scroll=True
        )

        self.add_user_dialog = ft.AlertDialog(
            title="Client",
            content=self.client_column,
            actions=[
                ft.Button(
                    "Salveaza",
                    on_click=self.on_save_btn_click,
                    icon=ft.Icons.SAVE,
                ),
                ft.TextButton(
                    "Anuleaza",
                    on_click=self.on_cancel_btn_click,
                    icon=ft.Icons.CANCEL,
                ),
            ]
        )
        self.is_company = False
        self.is_second_address = False

        self.all_clients = self.user_manager.get_all()
        self.list_of_clients = ft.ListView(
            controls=self.create_list(self.all_clients, self.on_edit_btn_click, self.on_delete_btn_click, self.on_view_btn_click),
            spacing=10,
            expand=True
        )

        self.view_name = ft.Text()
        self.view_email = ft.Text()
        self.view_phone = ft.Text()
        self.view_address = ft.Text()
        self.view_company_placeholder = ft.Column()
        self.view_second_address_placeholder = ft.Column()

        self.view_company_name = ft.Text()
        self.view_company_vat = ft.Text()
        self.view_company_rn = ft.Text()
        self.view_company_address = ft.Text()
        self.view_second_address = ft.Text()

        self.view_dialog = ft.AlertDialog(
            title=ft.Text("Vizualizeaza"),
            content=ft.Column(
                [
                    ft.Text("Utilizator:", weight=ft.FontWeight.BOLD),
                    self.view_name,
                    self.view_email,
                    self.view_phone,
                    self.view_address,
                    self.view_company_placeholder,
                    self.view_second_address_placeholder
                ],
                scroll=ft.ScrollMode.ADAPTIVE,
                width=400
            ),
            actions=[
                ft.Button("Ok", on_click=self.on_ok_btn_click)
            ]
        )

        self.delete_item_id = None

        self.confirm_delete_alert = ft.AlertDialog(
            title=ft.Text("Confirmati?"),
            actions=[
                ft.Button(
                    "Da",
                    on_click=self.on_delete_client_click,
                    icon=ft.Icons.DELETE,
                ),
                ft.TextButton(
                    "Nu",
                    on_click=self.on_delete_cancel_btn_click,
                    icon=ft.Icons.CANCEL,
                ),
            ]
        )

        self.edit_id = None

    def on_ok_btn_click(self, e):
        self.page.close(self.view_dialog)
        self.view_name.value = ''
        self.view_email.value = ''
        self.view_phone.value = ''
        self.view_address.value = ''
        self.view_company_placeholder.controls.clear()
        self.view_second_address_placeholder.controls.clear()

    def on_edit_btn_click(self, item):
        print(item)
        self.edit_id = item['id']
        prenume = ''
        if '~' in item['name']:
            prenume = item['name'].split('~')[0] 
        self.first_name.value=prenume
        
        nume = ''
        if '~' in item['name']:
            nume = item['name'].split('~')[1] 
        self.last_name.value=nume
        
        address = ''
        if item['address']:
            if "~" in item['address']:
                address = item['address'].split("~")[0].split("%")[1]
            else:
                address = item['address'].split("%")[1]
        self.address.value = address

        city = ''
        if item['address']:
            if "~" in item['address']:
                city = item['address'].split("~")[0].split("%")[0]
            else:
                city = item['address'].split("%")[0]
        self.city.value = city

        self.email.value = item['email']
        self.email.disabled = True
        self.phone.value = item['phone']
        company = self.company_manager.get_company(item['id'])
        if company:
            self.company_name.value = company['name']
            self.company_placeholder.controls.append(self.company_name)
            self.vat.value = company['vat']
            self.company_placeholder.controls.append(self.vat)
            self.register_number.value = company['register_number']
            self.company_placeholder.controls.append(self.register_number)
            self.company_address.value = company['address']
            self.company_placeholder.controls.append(self.company_address)
        if len(item['address'].split("~")) > 1:
            self.second_address.value = item['address'].split("~")[1]
            self.second_address_placeholder.controls.append(self.second_address)
        self.page.open(self.add_user_dialog)

    def on_delete_btn_click(self, id):
        self.delete_item_id = id
        self.page.open(self.confirm_delete_alert)

    def on_delete_client_click(self, e):
        self.user_manager.delete(self.delete_item_id)
        self.delete_item_id = None
        self.page.close(self.confirm_delete_alert)
        self.all_clients = self.user_manager.get_all()
        self.list_of_clients.controls = self.create_list(self.all_clients, self.on_edit_btn_click, self.on_delete_btn_click, self.on_view_btn_click)
        self.list_of_clients.update()

    def on_delete_cancel_btn_click(self, e):
        self.delete_item_id = None
        self.page.close(self.confirm_delete_alert)

    def on_view_btn_click(self, item):
        self.view_name.value = f"Nume: {item['name'].replace("~", " ")}"
        self.view_email.value = f"E-mail: {item['email']}"
        self.view_phone.value = f"Telefon: {item['phone']}"
        self.view_address.value = f"Adresa: {item['address'].split("~")[0].replace("%", ", ")}"
        company = self.company_manager.get_company(item['id'])
        if company:
            self.view_company_placeholder.controls.append(ft.Text(""))
            self.view_company_placeholder.controls.append(ft.Text("Date Companie:", weight=ft.FontWeight.BOLD))
            self.view_company_name.value = f"Denumire: {company['name']}"
            self.view_company_placeholder.controls.append(self.view_company_name)
            self.view_company_vat.value = f"CUI: {company['vat']}"
            self.view_company_placeholder.controls.append(self.view_company_vat)
            self.view_company_rn.value = f"Registru comertului: {company['register_number']}"
            self.view_company_placeholder.controls.append(self.view_company_rn)
            self.view_company_address.value = f"Sediu: {company['address']}"
            self.view_company_placeholder.controls.append(self.view_company_address)
        if len(item['address'].split("~")) > 1:
            self.view_second_address_placeholder.controls.append(ft.Text(""))
            self.view_second_address_placeholder.controls.append(ft.Text("Adresa Livrare:", weight=ft.FontWeight.BOLD))
            self.view_second_address.value = f"Adresa: {item['address'].split("~")[1]}"
            self.view_second_address_placeholder.controls.append(self.view_second_address)
        self.page.open(self.view_dialog)

    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.Column(
                            [
                                ft.Text(value=item['name'].replace("~", " "), weight=ft.FontWeight.BOLD),
                                ft.Text(value=item['email'], size=12)
                            ]
                        ),
             
                        ft.Row(
                            [
                                ft.IconButton(
                                    icon=ft.Icons.PREVIEW,
                                    on_click=lambda e, id=item: on_click_handler3(id),
                                ),
                                ft.IconButton(
                                    icon=ft.Icons.EDIT,
                                    on_click=lambda e, id=item: on_click_handler(id),
                                ),
                                ft.IconButton(
                                    icon=ft.Icons.DELETE,
                                    on_click=lambda e, id=item['id']: on_click_handler2(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_save_btn_click(self, e):
        user_name = self.first_name.value + "~" + self.last_name.value
        user_email = self.email.value
        user_phone = self.phone.value
        user_address = self.address.value
        company = {}
        
        company['name'] = self.company_name.value
        company['vat'] = self.vat.value
        company['register_number'] = self.register_number.value
        company['address'] = self.company_address.value
        delivery_address = self.second_address.value
        address = f'{user_address} ~ {delivery_address}'
        if self.edit_id:
            if len(delivery_address) == 0:
                self.user_manager.update_user_data(user_name, user_phone, user_address, self.edit_id)
            else:
                self.user_manager.update_user_data(user_name, user_phone, address, self.edit_id)
            exising_company = self.company_manager.get_company(self.edit_id)
            if exising_company:
                company['user_id'] = self.edit_id
                company['id'] = exising_company['id']
                self.company_manager.update_company(company)
        else:
            
            user_id = self.user_manager.invite_user(user_email, user_name, user_phone, user_address)
            print(user_id)
            if user_id:
                company['user_id'] = user_id
                if self.is_company:
                    self.company_manager.add_company(company)
                if self.is_second_address:
                    self.user_manager.update_user_data(user_name, user_phone, address, user_id)
        self.clear_fileds()
        self.page.close(self.add_user_dialog)
        self.all_clients = self.user_manager.get_all()
        self.list_of_clients.controls = self.create_list(self.all_clients, self.on_edit_btn_click, self.on_delete_btn_click, self.on_view_btn_click)
        self.list_of_clients.update()

    def on_cancel_btn_click(self, e):
        self.page.close(self.add_user_dialog)
        self.clear_fileds()
    
    def clear_fileds(self):
        self.first_name.value = ''
        self.first_name.update()
        self.last_name.value = ''
        self.last_name.update()
        self.email.value = ''
        self.email.update()
        self.phone.value = ''
        self.phone.update()
        self.address.value = ''
        self.address.update()
        try:
            self.company_name.value = ''
            self.company_name.update()
            self.vat.value = ''
            self.vat.update()
            self.register_number.value = ''
            self.register_number.update()
            self.company_address.value = ''
            self.company_address.update()
        except Exception as e:
            print(f'No company, Error: {e}')
        try:
            self.second_address.value = ''
            self.second_address.update()
        except Exception as e:
            print(f'No second address, Error: {e}')
        self.company_placeholder.controls.clear()
        self.company_placeholder.update()
        self.second_address_placeholder.controls.clear()
        self.second_address_placeholder.update()

    def on_is_comopany_btn_click(self, e):
        self.is_company = True
        self.company_placeholder.controls.append(ft.Text("Date firma"))
        self.company_placeholder.controls.append(self.company_name)
        self.company_placeholder.controls.append(self.vat)
        self.company_placeholder.controls.append(self.register_number)
        self.company_placeholder.controls.append(self.company_address)
        self.company_placeholder.update()

    def on_second_address(self, e):
        self.is_second_address = True
        self.second_address_placeholder.controls.append(ft.Text("Adresa de livrare"))
        self.second_address_placeholder.controls.append(
            self.second_address
        )
        self.second_address_placeholder.update()

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

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Clienti", 
                                weight=ft.FontWeight.BOLD, 
                                size=18
                            ),
                            ft.Button(
                                icon=ft.Icons.ADD,
                                text = "Invita",
                                on_click= self.on_add_btn_click
                            )
                        ],
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                    ),
                    self.list_of_clients
                ]
            )
        )