"""Panels und Add-on-Preferences.

Seit 1.6: Materialwahl als grosses Vorschau-Dropdown (template_icon_view),
die Werkzeuge liegen in einem zugeklappten "Utilities"-Unterpanel.
"""

import os

import bpy
from bpy.types import AddonPreferences

from .material import material_manager


def draw_material_panel(layout, context):
    szene = context.scene

    # Fehler beim Laden der CSV sichtbar machen (frueher nur in der Konsole).
    if material_manager.errors:
        err_box = layout.box()
        err_box.label(text=f"CSV-Fehler: {len(material_manager.errors)}", icon='ERROR')
        for msg in material_manager.errors[:5]:
            err_box.label(text=msg)
        if len(material_manager.errors) > 5:
            err_box.label(text="...")

    if not hasattr(szene, 'material_category'):
        layout.operator("material.reload_csv", text="Reload CSV", icon='FILE_REFRESH')
        return

    layout.prop(szene, 'material_category', text='Category')

    # Grosses Vorschau-Dropdown: Klick oeffnet das Bilderraster
    layout.template_icon_view(szene, 'basematerials_preview',
                              show_labels=True, scale=7.0, scale_popup=5.0)

    auswahl = getattr(szene, 'basematerials_preview', "")
    if auswahl and auswahl != "NONE":
        row = layout.row(align=True)
        op = row.operator("material.apply_material", text="Apply", icon='MATERIAL')
        op.material_name = auswahl
        color_op = row.operator("material.apply_color", text="", icon='BRUSH_DATA')
        color_op.material_name = auswahl
        update_op = row.operator("material.update_material", text="", icon='FILE_TICK')
        update_op.material_name = auswahl
        del_op = row.operator("material.delete_material", text="", icon='X')
        del_op.material_name = auswahl

    row = layout.row(align=True)
    row.operator("material.add_material_to_csv", text="Add to CSV", icon='ADD')
    row.operator("material.reload_csv", text="", icon='FILE_REFRESH')


def draw_utilities_panel(layout, context):
    col = layout.column(align=True)
    col.operator("material.apply_roughness_texture", text="Imperfection")
    col.operator("material.apply_scratches_texture", text="Scratches")
    col.separator()
    col.operator("material.shared_geo", text="Shared Geo")
    col.operator("material.kill_shared_geo", text="Kill Shared Geo")
    col.separator()
    col.operator("material.apply_random_uv", text="Random UV")
    col.operator("material.apply_random_brightness", text="Random Brightness")
    col.separator()
    col.operator("material.name_collection", text="Name Collection")
    col.operator("material.unhide_render", text="Unhide Render")


class MaterialPreferences(AddonPreferences):
    # Bei Extensions ist die bl_idname der Paketname (z. B. bl_ext.user_default.basematerials).
    bl_idname = __package__

    def draw(self, context):
        layout = self.layout
        row = layout.row()
        addon_dir = os.path.dirname(os.path.realpath(__file__))
        file_path = os.path.join(addon_dir, "materials.csv")
        row.operator("wm.path_open", text="Open Material CSV Folder").filepath = os.path.dirname(file_path)


class MATERIAL_PT_material_panel(bpy.types.Panel):
    bl_label = "Material Panel"
    bl_category = "BaseMaterials"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'

    def draw(self, context):
        draw_material_panel(self.layout, context)


class MATERIAL_PT_material_panel_node_editor(bpy.types.Panel):
    bl_label = "Material Panel"
    bl_category = "BaseMaterials"
    bl_space_type = 'NODE_EDITOR'
    bl_region_type = 'UI'

    def draw(self, context):
        draw_material_panel(self.layout, context)


class MATERIAL_PT_utilities(bpy.types.Panel):
    bl_label = "Utilities"
    bl_parent_id = "MATERIAL_PT_material_panel"
    bl_category = "BaseMaterials"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_options = {'DEFAULT_CLOSED'}

    def draw(self, context):
        draw_utilities_panel(self.layout, context)


class MATERIAL_PT_utilities_node_editor(bpy.types.Panel):
    bl_label = "Utilities"
    bl_parent_id = "MATERIAL_PT_material_panel_node_editor"
    bl_category = "BaseMaterials"
    bl_space_type = 'NODE_EDITOR'
    bl_region_type = 'UI'
    bl_options = {'DEFAULT_CLOSED'}

    def draw(self, context):
        draw_utilities_panel(self.layout, context)


class MATERIAL_PT_tracking(bpy.types.Panel):
    bl_label = "Object Tracking"
    bl_parent_id = "MATERIAL_PT_material_panel"
    bl_category = "BaseMaterials"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_options = {'DEFAULT_CLOSED'}

    def draw(self, context):
        col = self.layout.column()
        aktiv = getattr(context.scene, "basematerials_tracking", False)
        col.operator("material.toggle_tracking",
                     text="Tracking ausschalten" if aktiv else "Tracking einschalten",
                     icon='OBJECT_DATA', depress=aktiv)
        if aktiv:
            col.operator("material.update_tracking", text="Update", icon='FILE_REFRESH')


# Reihenfolge wichtig: Unterpanels NACH ihren Eltern-Panels registrieren.
# (Das Bake-AO-Panel registriert bake_ao.py selbst, ebenfalls als Unterpanel.)
UI_CLASSES = (
    MaterialPreferences,
    MATERIAL_PT_material_panel,
    MATERIAL_PT_material_panel_node_editor,
    MATERIAL_PT_utilities,
    MATERIAL_PT_utilities_node_editor,
    MATERIAL_PT_tracking,
)
