import customtkinter as ctk

class Chip(ctk.CTkButton):
    """
    CustomTkinter Chip component using CTkButton with rounded corners.
    Acts as a Choice Chip (selectable) or Filter Chip (removable not implemented here, but style is).
    """
    def __init__(self, master, text, command=None, command_right=None, command_double=None, 
                 selected=False, removable=False, **kwargs):
        self.is_selected = selected
        self.removable = removable
        self.user_command = command
        self.user_command_right = command_right
        self.user_command_double = command_double
        
        # 1. 중복 인자 방지를 위해 kwargs에서 기본값 추출 및 설정
        # 만약 외부(ChipGroup 등)에서 width나 height를 주면 그것을 쓰고, 없으면 기본값 사용
        width = kwargs.pop("width", 0) 
        height = kwargs.pop("height", 30)
        corner_radius = kwargs.pop("corner_radius", 15)
        border_width = kwargs.pop("border_width", 1)
        
        # 기본 스타일 색상
        self.default_fg = "transparent"
        self.default_text = ("gray10", "gray90")
        self.default_border = "gray70"
        
        # 활성(선택/삭제) 상태 색상
        self.active_fg = ("#3B8ED0", "#1F6AA5")
        self.active_text = "white"

        display_text = f"{text}  ✕" if removable else text

        # 2. 정리된 인자들로 부모 클래스 초기화
        super().__init__(
            master, 
            text=display_text, 
            command=self._handle_click,
            width=width,
            height=height,
            corner_radius=corner_radius,
            border_width=border_width,
            **kwargs
        )
        self.update_style()
        
        # 이벤트 바인딩
        if self.user_command_right:
            self.bind("<Button-3>", lambda e: self.user_command_right(text))
        if self.user_command_double:
            self.bind("<Double-Button-1>", lambda e: self.user_command_double(text))

    def _handle_click(self):
        """클릭 시 로직 분리: 삭제 모드면 바로 커맨드 실행, 아니면 토글"""
        text_val = self.cget("text").replace("  ✕", "").strip()
        if self.removable:
            if self.user_command: self.user_command(text_val)
        else:
            self.is_selected = not self.is_selected
            self.update_style()
            if self.user_command: self.user_command(text_val)

    def set_selected(self, selected):
        self.is_selected = selected
        self.update_style()
            
    def toggle_selection(self, *args):
        self.is_selected = not self.is_selected
        self.update_style()
        if self.user_command:
            self.user_command(self.cget("text")) # Pass text back

    def on_right_click(self, event):
        if self.user_command_right:
            self.user_command_right(self.cget("text"))

    def on_double_click(self, event):
        if self.user_command_double:
            self.user_command_double(self.cget("text"))

    def update_style(self):
        if self.removable or self.is_selected:
            self.configure(
                fg_color=self.active_fg,
                text_color=self.active_text,
                border_color=self.active_fg
            )
        else:
            self.configure(
                fg_color=self.default_fg,
                text_color=self.default_text,
                border_color=self.default_border
            )

    def _on_click(self):
        if self.user_command:
            self.user_command(self.cget("text").replace("  ✕", ""))

class ChipGroup(ctk.CTkFrame):
    """
    Manages a group of Chips.
    - Single selection mode (Raio)
    - Multi selection mode
    """
    def __init__(self, master, options=None, default=None, multi_select=False, command=None, 
                 command_right=None, command_double=None, **kwargs):
        super().__init__(master, fg_color="transparent", **kwargs)
        self.multi_select = multi_select
        self.command = command
        self.command_right = command_right
        self.command_double = command_double
        self.chips = []
        self.selected_values = []
        
        if default:
            self.selected_values = default if isinstance(default, list) else [default]
        
        if options is not None:
            self.refresh(options)

    def refresh(self, options):
        for chip in self.chips: chip.destroy()
        self.chips.clear()
        
        row, col = 0, 0
        max_cols = 5
        for opt in options:
            is_sel = opt in self.selected_values
            chip = Chip(
                self, text=opt, selected=is_sel,
                command=self.on_chip_click,
                command_right=self.command_right,
                command_double=self.command_double,
                width=60 # 여기서 width를 넘겨줘도 이제 충돌하지 않습니다.
            )
            chip.grid(row=row, column=col, padx=2, pady=2, sticky="ew")
            self.chips.append(chip)
            col += 1
            if col >= max_cols:
                col = 0
                row += 1

    def on_chip_click(self, value):
        if not self.multi_select:
            self.selected_values = [value]
            for chip in self.chips:
                chip.set_selected(chip.cget("text") == value)
        else:
            if value in self.selected_values: self.selected_values.remove(value)
            else: self.selected_values.append(value)
        
        if self.command: self.command(self.get())

    def get(self):
        if self.multi_select:
            return self.selected_values
        else:
            return self.selected_values[0] if self.selected_values else None

    def add_chip(self, text, remove_callback):
        """설정창에서 쓰는 동적 삭제형 칩 추가 (Pack 방식)"""
        chip = Chip(self, text=text, removable=True, command=remove_callback)
        chip.pack(side="left", padx=3, pady=3)
        self.chips.append(chip)

    def clear(self):
        for chip in self.chips:
            chip.destroy()
        self.chips = []
