import customtkinter as ctk
from PIL import Image
import os
from view.theme import theme_manager

class ImageViewerDialog(ctk.CTkToplevel):
    """이미지 파일을 보여주는 전용 뷰어 창"""
    def __init__(self, parent, image_path, title="이미지 뷰어"):
        super().__init__(parent)
        self.title(title)
        self.image_path = image_path
        
        # 창 크기 설정
        self.width = 800
        self.height = 700
        self._center_window()
        
        # 항상 위
        self.attributes('-topmost', True)
        if parent:
            self.transient(parent)
        self.lift()
        self.focus_force()
        
        # ESC 닫기
        self.bind("<Escape>", lambda e: self.destroy())

        # 메인 레이아웃
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        # 이미지 표시 영역
        self.main_frame = ctk.CTkFrame(self, fg_color="black")
        self.main_frame.grid(row=0, column=0, sticky="nsew", padx=10, pady=10)
        
        self.image_label = ctk.CTkLabel(self.main_frame, text="")
        self.image_label.pack(fill="both", expand=True)

        # 하단 컨트롤
        self.bottom_frame = ctk.CTkFrame(self, height=50)
        self.bottom_frame.grid(row=1, column=0, sticky="ew", padx=10, pady=(0, 10))
        
        ctk.CTkButton(
            self.bottom_frame, text="닫기", width=100, 
            fg_color="gray", command=self.destroy
        ).pack(side="right", padx=10, pady=10)
        
        self.info_label = ctk.CTkLabel(
            self.bottom_frame, text=os.path.basename(image_path),
            font=theme_manager.get_font(12)
        )
        self.info_label.pack(side="left", padx=20)

        # 이미지 로드 및 표시
        self._load_image()

    def _load_image(self):
        try:
            # 원본 이미지 로드
            pil_img = Image.open(self.image_path)
            
            # 비율 유지하며 리사이징
            orig_w, orig_h = pil_img.size
            ratio = min((self.width - 40) / orig_w, (self.height - 120) / orig_h)
            new_w = int(orig_w * ratio)
            new_h = int(orig_h * ratio)
            
            ctk_img = ctk.CTkImage(
                light_image=pil_img,
                dark_image=pil_img,
                size=(new_w, new_h)
            )
            
            self.image_label.configure(image=ctk_img)
            self.info_label.configure(text=f"{os.path.basename(self.image_path)} ({orig_w}x{orig_h})")
        except Exception as e:
            self.image_label.configure(text=f"이미지를 불러올 수 없습니다.\n{e}")

    def _center_window(self):
        self.update_idletasks()
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()
        x = (screen_width // 2) - (self.width // 2)
        y = (screen_height // 2) - (self.height // 2)
        self.geometry(f"{self.width}x{self.height}+{x}+{y}")
