import flet as ft
import os
import shutil

class Banner:
    def __init__(self, page: ft.Page):
        self.page = page

        self.banner_image = ft.Image(
            src='images/banner_placeholder.png',
            height=350,
            width=1000,
            fit=ft.ImageFit.COVER
        )

        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 = []

    def open_file_picker(self, e=None):
        self.file_dialog.pick_files(
            allow_multiple=False,
            allowed_extensions=["png", "jpg", "jpeg"]
        )
    
    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 on_upload_progress(self, e: ft.FilePickerUploadEvent):
        if e.progress == 1:
            print(f"Upload complete: {e.file_name}")

            base_path = os.getcwd()  # <-- The correct root path
            uploads_path = os.path.join(base_path, "uploads")
            assets_path = os.path.join(base_path, "assets", "images")
            os.makedirs(assets_path, exist_ok=True)

            source_file = os.path.join(uploads_path, e.file_name)
            destination_file2 = os.path.join(assets_path, e.file_name)
            destination_file = os.path.join(assets_path, 'banner.png')

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

            try:
                shutil.copy(source_file, destination_file2)
                shutil.move(source_file, destination_file)
                print(f"✅ File moved: {source_file} → {destination_file}")
                self.banner_image.src = f'images/{e.file_name}'
                self.banner_image.update()
                self.page.update()
                self.foto = e.file_name
            except Exception as ex:
                print(f"❌ Error moving file: {ex}")
    
    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    self.banner_image,
                    ft.Button(
                        "Adauga imagine",
                        on_click=self.open_file_picker,
                        icon=ft.Icons.UPLOAD
                    )
                ],
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                expand=True
            ),
            expand=True
        )