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

class Category:
    def __init__(self, page: ft.Page):
        self.page = page
        self.categories_manager = Categories()
        self.all_cateogies = self.categories_manager.get_categories()
        self.list_of_categories = ft.ListView(
            controls=self.create_list(self.all_cateogies, self.on_edit_btn_click, self.on_delete_btn_click),
            spacing=10,
            expand=True
        )
        self.foto = None 
        self.edit_id = 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.category_image = ft.Image(
            width=150, 
            height=150,
            src='images/placeholder.png',
        )

        self.category_name = ft.TextField(label="Denumire")

        self.add_dialog = ft.AlertDialog(
            title=ft.Text("Categorie"),
            content=ft.Column(
                [
                    ft.Row(
                        [
                            self.category_image,
                            ft.Button("Incarca", icon=ft.Icons.UPLOAD, on_click=self.open_file_picker)
                        ]
                    ),
                    self.category_name
                ],
                height=200,
                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.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_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.category_image.src = f'images/{e.file_name}'
                self.category_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_dialog)

    def on_save_btn_click(self, e):
        if self.category_image.src == 'images/placeholder.png' or self.category_name.value == '':
            return
        
        if self.edit_id is None:
            self.categories_manager.add(self.category_name.value, self.category_image.src)
        else:
            self.categories_manager.update(self.category_name.value, self.category_image.src, self.edit_id )
            self.edit_id = None
        
        self.page.close(self.add_dialog)
        self.category_image.src = 'images/placeholder.png'
        self.category_image.update()
        self.category_name.value = ''
        self.category_name.update()
        self.update_list()

    def on_cancel_btn_click(self, e):
        self.page.close(self.add_dialog)
        self.category_image.src = 'images/placeholder.png'
        self.category_image.update()
        self.category_name.value = ''
        self.category_name.update()

    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.Icon(ft.Icons.ARROW_RIGHT, size=20),
                                ft.Text(value=item['name'])
                            ]
                        ),
             
                        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,
                border = ft.border.all(1, ft.Colors.GREY),
                padding=10,
                border_radius=8,
            )
            for item in items
        ]
    
    def on_edit_btn_click(self, item):
        self.edit_id = item['id']
        self.category_name.value = item['name']
        self.category_image.src = item['image']
        self.page.open(self.add_dialog)

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

    def on_delete_product_click(self, e):
        self.categories_manager.delete(self.delete_item_id )
        self.delete_item_id = None
        self.page.close(self.confirm_delete_alert)
        print('Update list')
        self.update_list()

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

    def update_list(self):
        self.all_cateogies = self.categories_manager.get_categories()
        self.list_of_categories.controls.clear()
        self.list_of_categories.controls = self.create_list(self.all_cateogies, self.on_edit_btn_click, self.on_delete_btn_click)
        self.list_of_categories.update()
        self.page.update()

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            ft.Text("Categori", 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
                    ),
                    self.list_of_categories
                ],
                alignment=ft.MainAxisAlignment.START,
                expand=True
            ),
            expand=True,
        )