# FlightMonitor/gui/dialogs/import_progress_dialog.py
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from typing import Optional  # Per Optional[int] in update_progress
import os  # Per os.path.basename

# Se hai un logger comune per la GUI, potresti importarlo
# from ...utils.logger import get_logger
# logger = get_logger(__name__)
# Altrimenti, usa il logging standard se necessario per debug interno alla dialog
import logging

logger = logging.getLogger(__name__)


class ImportProgressDialog(tk.Toplevel):
    def __init__(
        self, parent, title="Importing Database...", file_name: Optional[str] = None
    ):
        super().__init__(parent)

        effective_title = title
        if file_name:
            effective_title = f"Importing: {os.path.basename(file_name)}"
        self.title(effective_title)

        self.parent = parent
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self._on_close_attempt)

        self.geometry("450x220")
        self.resizable(False, False)

        main_frame = ttk.Frame(self, padding="10 10 10 10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        ttk.Label(
            main_frame,
            text="Please wait while the aircraft database is being imported.",
        ).pack(pady=(0, 10))

        self.rows_processed_var = tk.StringVar(value="Rows Processed: 0")
        ttk.Label(main_frame, textvariable=self.rows_processed_var).pack(anchor=tk.W)

        self.rows_imported_var = tk.StringVar(value="Rows Imported/Updated: 0")
        ttk.Label(main_frame, textvariable=self.rows_imported_var).pack(
            anchor=tk.W, pady=(0, 10)
        )

        self.progress_var = tk.DoubleVar()
        self.progressbar = ttk.Progressbar(
            main_frame,
            orient="horizontal",
            length=400,
            mode="determinate",
            variable=self.progress_var,
        )
        self.progressbar.pack(pady=(0, 5), fill=tk.X, expand=True)
        self.progress_label_var = tk.StringVar(value="0/0 (0%)")
        ttk.Label(main_frame, textvariable=self.progress_label_var).pack(pady=(0, 10))

        self.status_message_var = tk.StringVar(value="Initializing import...")
        ttk.Label(
            main_frame, textvariable=self.status_message_var, wraplength=400
        ).pack(pady=(5, 0))

        self.close_button = ttk.Button(
            main_frame, text="Close", command=self.destroy, state=tk.DISABLED
        )
        self.close_button.pack(pady=(10, 0))

        self.import_running = False
        self.center_window()

    def center_window(self):
        self.update_idletasks()
        width = self.winfo_width()
        height = self.winfo_height()
        # Fallback se le dimensioni non sono ancora pronte
        if width <= 1:
            width = 450
        if height <= 1:
            height = 220

        x = (self.winfo_screenwidth() // 2) - (width // 2)
        y = (self.winfo_screenheight() // 2) - (height // 2)
        if width > 0 and height > 0:
            self.geometry(f"{width}x{height}+{x}+{y}")

    def update_progress(
        self,
        processed: int,
        imported: int,
        total_rows: Optional[int] = None,
        message: Optional[str] = None,
    ):
        if not self.winfo_exists():
            return
        self.rows_processed_var.set(f"Rows Processed: {processed}")
        self.rows_imported_var.set(f"Rows Imported/Updated: {imported}")
        if message:
            self.status_message_var.set(message)

        if total_rows is not None and total_rows > 0:
            self.progressbar["mode"] = "determinate"
            percentage = (processed / total_rows) * 100 if total_rows > 0 else 0
            self.progressbar["maximum"] = total_rows
            self.progress_var.set(processed)
            self.progress_label_var.set(f"{processed}/{total_rows} ({percentage:.1f}%)")
        elif total_rows == 0:
            self.progressbar["mode"] = "determinate"
            self.progressbar["maximum"] = 1
            self.progress_var.set(1)
            self.progress_label_var.set(f"0/0 (100%) - File empty or header only.")
        else:  # total_rows is None (conteggio iniziale fallito o non ancora fatto)
            if (
                not self.import_running or self.progressbar["mode"] != "indeterminate"
            ):  # Avvia solo se non già in indeterminate
                self.progressbar["mode"] = "indeterminate"
                self.progressbar.start(10)
            self.progress_label_var.set(f"Processed: {processed} (Total rows unknown)")

    def import_started(self):
        if not self.winfo_exists():
            return
        self.import_running = True
        self.status_message_var.set("Import in progress...")
        self.close_button.config(state=tk.DISABLED)
        self.progressbar["mode"] = "indeterminate"
        self.progressbar.start(10)

    def import_finished(self, success: bool, final_message: str):
        if not self.winfo_exists():
            return
        self.import_running = False
        self.status_message_var.set(final_message)
        self.progressbar.stop()
        self.progressbar["mode"] = "determinate"
        if success and self.progressbar["maximum"] > 0:
            # Se il massimo era > 0, imposta il valore al massimo per mostrare il 100%
            # Questo accade se total_rows era stato calcolato.
            current_max = self.progressbar["maximum"]
            self.progress_var.set(current_max)
        elif (
            success and self.progressbar["maximum"] == 0
        ):  # File vuoto gestito in update_progress
            self.progress_var.set(0)  # o 1 se maximum è 1
            if self.progressbar["maximum"] == 1:
                self.progress_var.set(1)

        self.close_button.config(state=tk.NORMAL)

    def _on_close_attempt(self):
        if self.import_running:
            messagebox.showwarning(
                "Import in Progress",
                "Import is currently running. Please wait for it to complete.",
                parent=self,
            )
        else:
            self.destroy()


if __name__ == "__main__":
    # Simple test for the dialog
    root = tk.Tk()
    root.withdraw()  # Hide main window for dialog test

    def test_dialog():
        dialog = ImportProgressDialog(root, file_name="my_test_file.csv")

        dialog.import_started()
        dialog.update_progress(0, 0, message="Counting rows...")

        def update_after_delay(p, i, t, msg, finished=False, success=True):
            if dialog.winfo_exists():
                dialog.update_progress(p, i, t, msg)
                if finished:
                    dialog.import_finished(success, msg)

        # Simulate row counting
        root.after(2000, lambda: update_after_delay(0, 0, 5000, "Importing..."))

        # Simulate progress
        for i in range(1, 6):
            processed_count = i * 1000
            imported_count = i * 990  # Simula qualche errore
            root.after(
                2000 + i * 1500,
                lambda p=processed_count, imp=imported_count: update_after_delay(
                    p, imp, 5000, f"Processing item {p}..."
                ),
            )

        root.after(
            2000 + 5 * 1500 + 1000,
            lambda: update_after_delay(
                5000, 4950, 5000, "Import complete!", finished=True, success=True
            ),
        )

    # Button to open the dialog (since root is withdrawn)
    test_button = ttk.Button(
        tk.Toplevel(root), text="Open Import Dialog Test", command=test_dialog
    )
    test_button.pack(padx=20, pady=20)

    root.mainloop()
