import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from pathlib import Path

class ParameterDialog:
    def __init__(self, columns, current_column, on_confirm):
        self.columns = columns
        self.current_column = current_column
        self.on_confirm_callback = on_confirm
        self.selected_value = None
        self.png_folder = Path('png')
        self.current_image = None
        self.image_label = None

    def _bind_mousewheel(self, canvas):
        def _on_mousewheel(event):
            if event.delta:
                canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
            else:
                if event.num == 4:
                    canvas.yview_scroll(-1, "units")
                elif event.num == 5:
                    canvas.yview_scroll(1, "units")

        canvas.bind_all("<MouseWheel>", _on_mousewheel)
        canvas.bind_all("<Button-4>", _on_mousewheel)
        canvas.bind_all("<Button-5>", _on_mousewheel)

    def _update_image(self, *args):
        """선택된 파라미터에 해당하는 PNG 이미지 표시"""
        selected = self.selected_var.get()
        png_path = self.png_folder / f"{selected}.png"
        
        if png_path.exists() and self.image_label:
            try:
                # 이미지 로드 및 리사이즈
                img = Image.open(png_path)
                # 최대 크기 설정 (비율 유지)
                max_size = (500, 400)
                img.thumbnail(max_size, Image.LANCZOS)
                
                # PhotoImage로 변환
                self.current_image = ImageTk.PhotoImage(img)
                self.image_label.config(image=self.current_image)
            except Exception as e:
                print(f"이미지 로드 실패: {e}")

    def show(self):
        # ================= Window =================
        self.dialog = tk.Tk()
        self.dialog.title("Set Parameter")
        self.dialog.geometry("1100x550")
        self.dialog.resizable(True, True)
        self.dialog.configure(bg='#f7f7f7')
        self.dialog.attributes('-topmost', True)

        # ================= Header =================
        header_frame = tk.Frame(self.dialog, bg='#0072B5', height=50)
        header_frame.pack(fill=tk.X)
        header_frame.pack_propagate(False)

        tk.Label(
            header_frame,
            text="Set Parameter",
            font=('Arial', 14, 'bold'),
            bg='#0072B5',
            fg='white'
        ).pack(pady=12)

        # ================= Main Container =================
        main_container = tk.Frame(self.dialog, bg='#f7f7f7')
        main_container.pack(fill=tk.BOTH, expand=True, padx=15, pady=(10, 0))

        # ================= Left: Scroll Area =================
        scroll_container = tk.Frame(main_container, bg='white', width=500)
        scroll_container.pack(side=tk.LEFT, fill=tk.BOTH, expand=False, padx=(0, 10))
        scroll_container.pack_propagate(False)

        canvas = tk.Canvas(scroll_container, bg='white', highlightthickness=0)
        scrollbar = tk.Scrollbar(scroll_container, orient="vertical", command=canvas.yview)
        content_frame = tk.Frame(canvas, bg='white')

        content_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )

        canvas.create_window((0, 0), window=content_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        self._bind_mousewheel(canvas)

        # ================= Content =================
        tk.Label(
            content_frame,
            text="Parameter",
            font=('Arial', 10, 'bold'),
            bg='white',
            fg='#333333'
        ).pack(anchor=tk.W, pady=(10, 5))

        tk.Frame(content_frame, height=2, bg='#e0e0e0').pack(fill=tk.X, pady=(0, 15))

        radio_frame = tk.Frame(content_frame, bg='white')
        radio_frame.pack(fill=tk.X)

        for i in range(3):
            radio_frame.columnconfigure(i, weight=1, minsize=140)

        self.selected_var = tk.StringVar(value=self.current_column)
        # 선택 변경 시 이미지 업데이트
        self.selected_var.trace('w', self._update_image)

        for i, col in enumerate(self.columns):
            tk.Radiobutton(
                radio_frame,
                text=col,
                variable=self.selected_var,
                value=col,
                font=('Arial', 9),
                bg='white',
                activebackground='white',
                borderwidth=0,
                highlightthickness=0
            ).grid(
                row=i // 3,
                column=i % 3,
                sticky=tk.W,
                padx=10,
                pady=8
            )

        # ================= Right: Image Display =================
        image_container = tk.Frame(main_container, bg='white', relief=tk.SUNKEN, borderwidth=1)
        image_container.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

        # 이미지 제목
        tk.Label(
            image_container,
            text="Parameter Visualization",
            font=('Arial', 12, 'bold'),
            bg='white',
            fg='#0072B5'
        ).pack(pady=10)

        # 이미지 표시 영역
        self.image_label = tk.Label(image_container, bg='white')
        self.image_label.pack(pady=20, padx=20, expand=True)

        # 초기 이미지 로드
        self._update_image()

        # ================= Button (Fixed) =================
        button_frame = tk.Frame(self.dialog, bg='#f7f7f7')
        button_frame.pack(fill=tk.X, padx=15, pady=10)

        ok_button = tk.Button(
            button_frame,
            text="Ok",
            command=self._on_ok,
            font=('Arial', 10, 'bold'),
            bg='#0072B5',
            fg='white',
            activebackground='#005a8f',
            activeforeground='white',
            relief=tk.FLAT,
            cursor='hand2',
            width=20,
            height=2
        )
        ok_button.pack(pady=5)

        ok_button.bind("<Enter>", lambda e: ok_button.config(bg='#005a8f'))
        ok_button.bind("<Leave>", lambda e: ok_button.config(bg='#0072B5'))

        self.dialog.protocol("WM_DELETE_WINDOW", self._on_cancel)
        self.dialog.mainloop()

    def _on_ok(self):
        self.selected_value = self.selected_var.get()
        self.dialog.destroy()
        if self.on_confirm_callback:
            self.on_confirm_callback(self.selected_value)

    def _on_cancel(self):
        self.dialog.destroy()



class AxisParameterDialog:
    def __init__(self, columns, current_x, current_y, on_confirm):
        self.columns = columns
        self.current_x = current_x
        self.current_y = current_y
        self.on_confirm_callback = on_confirm
        self.png_folder = Path('png')
        self.current_x_image = None
        self.current_y_image = None
        self.x_image_label = None
        self.y_image_label = None

    def _bind_mousewheel(self, canvas):
        def _on_mousewheel(event):
            if event.delta:
                canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
            else:
                if event.num == 4:
                    canvas.yview_scroll(-1, "units")
                elif event.num == 5:
                    canvas.yview_scroll(1, "units")

        canvas.bind_all("<MouseWheel>", _on_mousewheel)
        canvas.bind_all("<Button-4>", _on_mousewheel)
        canvas.bind_all("<Button-5>", _on_mousewheel)

    def _update_x_image(self, *args):
        """X축 파라미터에 해당하는 PNG 이미지 표시"""
        selected = self.x_var.get()
        png_path = self.png_folder / f"{selected}.png"
        
        if png_path.exists() and self.x_image_label:
            try:
                img = Image.open(png_path)
                max_size = (400, 250)  # 영역에 맞게 크기 증가
                img.thumbnail(max_size, Image.LANCZOS)
                
                self.current_x_image = ImageTk.PhotoImage(img)
                self.x_image_label.config(image=self.current_x_image)
            except Exception as e:
                print(f"X 이미지 로드 실패: {e}")

    def _update_y_image(self, *args):
        """Y축 파라미터에 해당하는 PNG 이미지 표시"""
        selected = self.y_var.get()
        png_path = self.png_folder / f"{selected}.png"
        
        if png_path.exists() and self.y_image_label:
            try:
                img = Image.open(png_path)
                max_size = (400, 250)  # 영역에 맞게 크기 증가
                img.thumbnail(max_size, Image.LANCZOS)
                
                self.current_y_image = ImageTk.PhotoImage(img)
                self.y_image_label.config(image=self.current_y_image)
            except Exception as e:
                print(f"Y 이미지 로드 실패: {e}")

    def show(self):
        self.dialog = tk.Tk()
        self.dialog.title("Set Parameters")
        self.dialog.geometry("1100x700")
        self.dialog.resizable(True, True)
        self.dialog.configure(bg='#f7f7f7')
        self.dialog.attributes('-topmost', True)

        # ================= Header =================
        header = tk.Frame(self.dialog, bg='#0072B5', height=50)
        header.pack(fill=tk.X)
        header.pack_propagate(False)

        tk.Label(
            header,
            text="Set Parameters",
            font=('Arial', 14, 'bold'),
            bg='#0072B5',
            fg='white'
        ).pack(pady=12)

        # ================= Main Container =================
        main_container = tk.Frame(self.dialog, bg='#f7f7f7')
        main_container.pack(fill=tk.BOTH, expand=True, padx=15, pady=(10, 0))

        # ================= Left: Scroll Area =================
        scroll_container = tk.Frame(main_container, bg='white', width=550)
        scroll_container.pack(side=tk.LEFT, fill=tk.BOTH, expand=False, padx=(0, 10))
        scroll_container.pack_propagate(False)

        canvas = tk.Canvas(scroll_container, bg='white', highlightthickness=0)
        scrollbar = tk.Scrollbar(scroll_container, orient="vertical", command=canvas.yview)
        content = tk.Frame(canvas, bg='white')

        content.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )

        canvas.create_window((0, 0), window=content, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        self._bind_mousewheel(canvas)

        # ================= X Axis =================
        tk.Label(
            content,
            text="X Axis Parameter",
            font=('Arial', 10, 'bold'),
            bg='white'
        ).pack(anchor=tk.W, pady=(5, 5))

        tk.Frame(content, height=2, bg='#e0e0e0').pack(fill=tk.X, pady=(0, 10))

        x_frame = tk.Frame(content, bg='white')
        x_frame.pack(fill=tk.X)

        self.x_var = tk.StringVar(value=self.current_x)
        self.x_var.trace('w', self._update_x_image)

        for i in range(3):
            x_frame.columnconfigure(i, weight=1, minsize=160)

        for i, col in enumerate(self.columns):
            tk.Radiobutton(
                x_frame,
                text=col,
                variable=self.x_var,
                value=col,
                font=('Arial', 9),
                bg='white',
                activebackground='white',
                borderwidth=0,
                highlightthickness=0
            ).grid(row=i // 3, column=i % 3, sticky=tk.W, padx=10, pady=6)

        # ================= Y Axis =================
        tk.Label(
            content,
            text="Y Axis Parameter",
            font=('Arial', 10, 'bold'),
            bg='white'
        ).pack(anchor=tk.W, pady=(15, 5))

        tk.Frame(content, height=2, bg='#e0e0e0').pack(fill=tk.X, pady=(0, 10))

        y_frame = tk.Frame(content, bg='white')
        y_frame.pack(fill=tk.X)

        self.y_var = tk.StringVar(value=self.current_y)
        self.y_var.trace('w', self._update_y_image)

        for i in range(3):
            y_frame.columnconfigure(i, weight=1, minsize=160)

        for i, col in enumerate(self.columns):
            tk.Radiobutton(
                y_frame,
                text=col,
                variable=self.y_var,
                value=col,
                font=('Arial', 9),
                bg='white',
                activebackground='white',
                borderwidth=0,
                highlightthickness=0
            ).grid(row=i // 3, column=i % 3, sticky=tk.W, padx=10, pady=6)

        # ================= Right: Image Display =================
        image_container = tk.Frame(main_container, bg='white')
        image_container.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # Grid 설정: 2행 1열, 각 행이 50%씩
        image_container.rowconfigure(0, weight=1)
        image_container.rowconfigure(1, weight=1)
        image_container.columnconfigure(0, weight=1)

        # ================= X Axis 영역 (상단 50%) =================
        x_frame = tk.Frame(image_container, bg='white')
        x_frame.grid(row=0, column=0, sticky='nsew', padx=5, pady=(5, 2))
        
        tk.Label(
            x_frame,
            text="X Axis Visualization",
            font=('Arial', 11, 'bold'),
            bg='white',
            fg='#0072B5'
        ).pack(pady=(5, 10))

        self.x_image_label = tk.Label(x_frame, bg='white')
        self.x_image_label.pack(expand=True, fill=tk.BOTH)

        # ================= 구분선 (X와 Y 사이) =================
        separator = tk.Frame(image_container, bg='#e0e0e0', height=1)
        separator.grid(row=0, column=0, sticky='ews', pady=0)

        # ================= Y Axis 영역 (하단 50%) =================
        y_frame = tk.Frame(image_container, bg='white')
        y_frame.grid(row=1, column=0, sticky='nsew', padx=5, pady=(2, 5))
        
        tk.Label(
            y_frame,
            text="Y Axis Visualization",
            font=('Arial', 11, 'bold'),
            bg='white',
            fg='#0072B5'
        ).pack(pady=(5, 10))

        self.y_image_label = tk.Label(y_frame, bg='white')
        self.y_image_label.pack(expand=True, fill=tk.BOTH)

        # 초기 이미지 로드
        self._update_x_image()
        self._update_y_image()

        # ================= Button (Fixed) =================
        button_frame = tk.Frame(self.dialog, bg='#f7f7f7')
        button_frame.pack(fill=tk.X, padx=15, pady=10)

        tk.Button(
            button_frame,
            text="Ok",
            command=self._on_ok,
            font=('Arial', 10, 'bold'),
            bg='#0072B5',
            fg='white',
            activebackground='#005a8f',
            relief=tk.FLAT,
            cursor='hand2',
            width=20,
            height=2
        ).pack()

        self.dialog.protocol("WM_DELETE_WINDOW", self._on_cancel)
        self.dialog.mainloop()

    def _on_ok(self):
        self.dialog.destroy()
        if self.on_confirm_callback:
            self.on_confirm_callback(self.x_var.get(), self.y_var.get())

    def _on_cancel(self):
        self.dialog.destroy()