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

class ProductsPage:
    def __init__(self, page: ft.Page):
        self.page = page
        self.category_manager = Categories()
        self.product_manager = Products()

        self.name = ft.TextField(label="Denumire")
        self.description = ft.TextField(label="Descriere", multiline=True, min_lines=3, max_lines=5)
        self.details = ft.TextField(label="Detalii", multiline=True, min_lines=3, max_lines=5)
        self.price = ft.TextField(label="Pret")
        self.discount = ft.TextField(label="Reducere (%)", value='0')
        self.quantity = ft.TextField(label="Cantitate")
        self.search_filed = ft.TextField(label="Cauta Produs", on_submit=self.on_search_btn_click, expand=True)
        self.search_btn = ft.IconButton(icon=ft.Icons.SEARCH, on_click=self.on_search_btn_click)
        self.product_image = ft.Image(
            width=150, 
            height=150,
            src='images/placeholder.png',
        )

        self.aviability = ft.Dropdown(
            label='Disonibilitate',
            options=[
                ft.dropdown.Option(key='in_stock', text="In stoc"),
                ft.dropdown.Option(key='in_provider_stock', text="In stoc la furnizor"),
                ft.dropdown.Option(key='not_available', text="Indisponibil"),
            ],
            expand=True
        )
        self.aviability.value = 'in_stock'

        self.category = ft.Dropdown(
            label="Categorie",
            options=self.get_categories(),
            expand=True
        )


        self.add_product_dialog = ft.AlertDialog(
            title=ft.Text("Produs"),
            content=ft.Column(
                [
                    ft.Row(
                        [
                            self.product_image,
                            ft.Button("Incarca", icon=ft.Icons.UPLOAD, on_click=self.open_file_picker)
                        ]
                    ),
                    self.name,
                    self.category,
                    self.description,
                    self.details,
                    self.price,
                    self.discount,
                    self.quantity,
                    self.aviability,
                ],
                scroll=ft.ScrollMode.ADAPTIVE,
                width=400
            ),
            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.foto = None 
        self.file_dialog = ft.FilePicker(
            on_result=self.on_file_picker_result,
            on_upload=self.on_upload_progress
        )
        self.page.overlay.append(self.file_dialog)
        self.page.update()  # Required to register the FilePicker control

        self.uploaded_files = []

        self._all_products = self.product_manager.get_all()
        self.products_list = ft.ListView(
            controls=self.create_list(self._all_products, self.edit_product, self.delete_product),
            spacing=10,
            expand=True
            )
        
        self.edit_item_id = None
        self.delete_item_id = None

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

    def on_search_btn_click(self, e):
        search = self.search_filed.value
        buffer = []
        for product in self._all_products:
            if search.lower() in product['name'].lower():
                buffer.append(product)
        self.products_list.controls.clear()
        self.search_filed.value = ''
        self.search_filed.update()
        self._all_products = self.product_manager.get_all()
        self.products_list.controls=self.create_list(buffer, self.edit_product, self.delete_product)
        self.products_list.update()

    def on_file_picker_result(self, e: ft.FilePickerResultEvent):
        if e.files:
            file = e.files[0]
            file_name = file.name
            upload_url = self.page.get_upload_url(file_name, 600)

            print(f"Uploading {file_name} to {upload_url}")

            upload_task = ft.FilePickerUploadFile(
                name=file.name,
                upload_url=upload_url
            )
            self.file_dialog.upload([upload_task])

    def open_file_picker(self, e=None):
        self.file_dialog.pick_files(
            allow_multiple=False,
            allowed_extensions=["png", "jpg", "jpeg"]
        )

    def on_upload_progress(self, e: ft.FilePickerUploadEvent):
        if e.progress == 1:
            print(f"Upload complete: {e.file_name}")

            # Resolve paths relative to the UI folder (two levels up from this file)
            ui_root = os.path.dirname(os.path.dirname(__file__))
            uploads_path = os.path.join(ui_root, "uploads")
            assets_path = os.path.join(ui_root, "assets", "images")
            os.makedirs(assets_path, exist_ok=True)

            source_file = os.path.join(uploads_path, e.file_name)
            destination_file = os.path.join(assets_path, e.file_name)

            if not os.path.exists(source_file):
                print(f"❌ File not found: {source_file}")
                return

            try:
                shutil.move(source_file, destination_file)
                print(f"✅ File moved: {source_file} → {destination_file}")
                self.product_image.src = f'images/{e.file_name}'
                self.product_image.update()
                self.page.update()
                self.foto = e.file_name
            except Exception as ex:
                print(f"❌ Error moving file: {ex}")

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

    def on_save_btn_click(self, e):
        product = {
            'name': self.name.value,
            'description': self.description.value,
            'details': self.details.value,
            'price' : self.price.value,
            'discount' : self.discount.value,
            'quantity' : self.quantity.value,
            'image' : self.product_image.src,
            'aviability' : self.aviability.value,
            'category_id' : self.category.value
        }
        print(product)
        if self.edit_item_id == None:
            self.product_manager.add(product)
        else:
            self.product_manager.update(product, self.edit_item_id)
            self.edit_item_id = None

        self.page.close(self.add_product_dialog)
        self.set_popup_to_default()
    
        print('Update list')
        self._all_products = self.product_manager.get_all()
        self.products_list.controls=self.create_list(self._all_products, self.edit_product, self.delete_product)
        self.products_list.update()

    def on_cancel_btn_click(self, e):
        self.page.close(self.add_product_dialog)
        self.set_popup_to_default()
        if self.edit_item_id != None:
            self.edit_item_id = None
        
    def set_popup_to_default(self):
        self.name.value = ''
        self.name.update()
        self.description.value = ''
        self.description.update()
        self.details.value = ''
        self.details.update()
        self.price.value = ''
        self.price.update()
        self.discount.value = ''
        self.discount.update()
        self.quantity.value = ''
        self.quantity.update()
        self.product_image.src = 'images/placeholder.png'
        self.product_image.update()
        self.aviability.value = None
        self.aviability.update()
        self.category.value = None
        self.category.update()


    def get_categories(self):
        categories = self.category_manager.get_categories()
        return [
            ft.dropdown.Option(key=cat['id'], text=cat['name'])
            for cat in categories
        ] 
    
    def create_list(self, items, on_click_handler, on_click_handler2):
        """Helper to create list items for a column."""
        return [
            ft.Container(
                content=ft.Row(
                    [
                        ft.Row(
                            [
                                ft.Image(
                                    src=item['image'], 
                                    width=50, 
                                    height=50, 
                                    fit=ft.ImageFit.COVER,
                                    border_radius=5
                                ),
                                ft.Column(
                                    [
                                        ft.Text(value=item['name'], weight=ft.FontWeight.BOLD, size=15),
                                        ft.Text(value=f"Pret: {item['price']}", size=12)
                                    ]
                                ),
                            ]
                        ),
                        ft.Row(
                            [
                                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,
                padding=10,
                border_radius=8,
                border = ft.border.all(1, ft.Colors.GREY),
            )
            for item in items
        ]
    
    def edit_product(self, item):
        self.edit_item_id = item['id']
        self.name.value = item['name']
        self.description.value = item['description']
        self.details.value = item['details']
        self.price.value = item['price']
        self.discount.value = item['discount']
        self.quantity.value = item['quantity']
        self.product_image.src = item['image']
        self.aviability.value = item['aviability']
        self.category.value = item['category_id']
        self.page.open(self.add_product_dialog)

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

    def on_delete_product_click(self, e):
        self.product_manager.delete(self.delete_item_id )
        self.delete_item_id = None
        self.page.close(self.confirm_delete_alert)
        print('Update list')
        self._all_products = self.product_manager.get_all()
        self.products_list.controls=self.create_list(self._all_products, self.edit_product, self.delete_product)
        self.products_list.update()

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

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Produse", size=18, weight=ft.FontWeight.BOLD),
                            ft.Button("Adauga", icon=ft.Icons.ADD, on_click=self.on_add_btn_click),
                        ],
                        alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                    ),
                    ft.Row(
                        [
                            self.search_filed,
                            self.search_btn,
                        ]
                    ),
                    self.products_list
                ],
                alignment=ft.MainAxisAlignment.START,
                expand=True
            ),
            expand=True,
        )