import bpy


class VIEW3D_PT_hi3d_model_manager(bpy.types.Panel):
    bl_label = "Hi3D Model Manager"
    bl_idname = "VIEW3D_PT_hi3d_model_manager"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "Hi3D Model Manager"

    def draw(self, context):
        layout = self.layout
        scene = context.scene

        header = layout.row(align=True)
        header.label(text="Generated Tasks")
        layout.template_list("HI3D_UL_task_list", "", scene, "hi3d_tasks", scene, "hi3d_selected_task_index", rows=4)
        details = layout.box()
        details.label(text="Task Info:")
        tasks = getattr(scene, "hi3d_tasks", [])
        idx = getattr(scene, "hi3d_selected_task_index", 0)
        if len(tasks) > 0:
            idx = max(0, min(idx, len(tasks) - 1))
            item = tasks[idx]
            details.label(text=f"TaskID:  {item.task_id}")
            details.label(text=f"Task Type:  {item.task_type}")
            details.label(text=f"Create Time:  {item.create_time}")
            if item.image:
                details.template_ID_preview(item, "image")
        
        header2 = layout.row(align=True)
        header2.label(text="Texture Tasks")
        layout.template_list("HI3D_UL_texture_task_list", "", scene, "hi3d_texture_tasks", scene, "hi3d_selected_texture_task_index", rows=4)
        details2 = layout.box()
        details2.label(text="Task Info:")
        tasks2 = getattr(scene, "hi3d_texture_tasks", [])
        idx2 = getattr(scene, "hi3d_selected_texture_task_index", 0)
        if len(tasks2) > 0:
            idx2 = max(0, min(idx2, len(tasks2) - 1))
            item2 = tasks2[idx2]
            details2.label(text=f"TaskID:  {item2.task_id}")
            details2.label(text=f"Task Type:  {item2.task_type}")
            details2.label(text=f"Create Time:  {item2.create_time}")
            if item2.image:
                details2.template_ID_preview(item2, "image")
                is_replacing = getattr(scene, "hi3d_is_replacing_texture", False)
                can_replace = getattr(item2, "tex_status", "") in {"DONE", "FAIL"}
                op_row = details2.row(align=True)
                op_row.enabled = (not is_replacing) and can_replace
                if is_replacing:
                    op_row.operator("hi3d.reload_texture_image", text="Generating...")
                else:
                    tex_text = "Replace Texture Image (cost:{})".format(getattr(scene, "hi3d_texture_cost", 0))
                    op_row.operator("hi3d.reload_texture_image", text=tex_text)
                
                details2.label(text=f"Generating texture will create a new texture version. ")
                details2.label(text=f"And replace the current materials on the object.")
        
        link = layout.column(align=True)
        link.label(text="Session-only tasks are shown here.")
        link.label(text="View full task history on the API page.")
        link.operator("hi3d.open_billing", text="API page")

class VIEW3D_PT_hi3d_model_generator(bpy.types.Panel):
    bl_label = "Hi3D Model Generator"
    bl_idname = "VIEW3D_PT_hi3d_model_generator"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "Hi3D Model Generator"

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        banner = getattr(scene, "hi3d_banner", None)
        if banner:
            layout.template_preview(banner, show_buttons=False)
        box = layout.box()
        row = box.row(align=True)
        row.operator("hi3d.view_tutorial", text="View Tutorial", icon='HELP')

        row = box.row(align=True)
        row.label(text="User Balance:")
        row.label(text=str(getattr(scene, "hi3d_balance", 0)))
        row.operator("hi3d.open_billing", text="Go Billing")
        row2 = box.row(align=True)
        row2.prop(scene, "hi3d_access_key", text="Access Key")
        row3 = box.row(align=True)
        row3.prop(scene, "hi3d_secret_key", text="Secret Key")
        
        row_confirm = layout.row()
        row_confirm.enabled = not getattr(scene, "hi3d_confirmed", False)
        row_confirm.operator("hi3d.confirm_api_key", text="Confirm")
        
        if getattr(scene, "hi3d_confirmed", False):
            box2 = layout.box()
            row_model = box2.row(align=True)
            
            row_model.label(text="Model Type")
            row_model.prop(scene, "hi3d_model_type", text="")

            rtop = box2.row(align=True)
            op1 = rtop.operator("hi3d.set_task", text="Image to 3D", depress=getattr(scene, "hi3d_task_type", "IMAGE") == "IMAGE")
            op1.task = "IMAGE"
            op2 = rtop.operator("hi3d.set_task", text="Multi-view to 3D", depress=getattr(scene, "hi3d_task_type", "IMAGE") == "MULTI")
            op2.task = "MULTI"
            if getattr(scene, "hi3d_task_type", "IMAGE") == "IMAGE":
                row2_1 = box2.row()
                row2_1.template_ID_preview(scene, "hi3d_input_image", open="hi3d.load_image")
            else:
                row2_2 = box2.row()
                split1 = row2_2.split(factor=0.5)

                # FRONT IMAGE
                col_front = split1.column(align=True)
                label_row = col_front.row()
                label_row.alignment = "CENTER"
                label_row.label(text="FRONT(necessary)")
                row2_3 = col_front.row()
                row2_3.template_ID_preview(
                    scene, "front_image", open="hi3d.load_front_image"
                )

                # BACK IMAGE
                col_back = split1.column(align=True)
                label_row = col_back.row()
                label_row.alignment = "CENTER"
                label_row.label(text="BACK")
                row2_4 = col_back.row()
                row2_4.template_ID_preview(
                    scene, "back_image", open="hi3d.load_back_image"
                )

                row2_5 = box2.row()
                split2 = row2_5.split(factor=0.5)

                # LEFT IMAGE
                col_left = split2.column(align=True)
                label_row = col_left.row()
                label_row.alignment = "CENTER"
                label_row.label(text="LEFT")
                row2_6 = col_left.row()
                row2_6.template_ID_preview(
                    scene, "left_image", open="hi3d.load_left_image"
                )

                # RIGHT IMAGE
                col_right = split2.column(align=True)
                label_row = col_right.row()
                label_row.alignment = "CENTER"
                label_row.label(text="RIGHT")
                row2_7 = col_right.row()
                row2_7.template_ID_preview(
                    scene, "right_image", open="hi3d.load_right_image"
                )

            rver = box2.row(align=True)
            rver.label(text="Model Version")
            rver.prop(scene, "hi3d_model_version", text="")
            rres = box2.row(align=True)
            rres.label(text="Resolution")
            rres.prop(scene, "hi3d_resolution", text="")
            rface = box2.row(align=True)
            rface.prop(scene, "hi3d_face_limit", text=f"Face Limit", slider=True)
            is_generating = getattr(scene, "hi3d_is_generating", False)
            if is_generating:
                gen_text = "Generating..."
            else:
                gen_text = "Generate (cost:{})".format(getattr(scene, "hi3d_generate_cost", 0))
            row_gen = box2.row(align=True)
            row_gen.enabled = not is_generating
            row_gen.operator("hi3d.generate_model", text=gen_text)

class VIEW3D_PT_hi3d_texture_generator(bpy.types.Panel):
    bl_label = "Hi3D Texture Generator"
    bl_idname = "VIEW3D_PT_hi3d_texture_generator"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "Hi3D Texture Generator"

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        if getattr(scene, "hi3d_confirmed", False):
            header = layout.row(align=True)
            header.label(text="Choose One Object -> Add to Texture Task")
            header.operator("hi3d.add_texture_task", text="Add Object")
            name_row = layout.row(align=True)
            name_row.prop(scene, "hi3d_last_added_object_name", text="Object Name")
            details = layout.box()
            details.label(text="Task Info:")
            details.label(text=f"TaskID:  {getattr(scene, 'hi3d_selected_texture_task_id', '') or 'None'}")
            details.label(text=f"Task Type:  {getattr(scene, 'hi3d_selected_texture_task_type', '') or 'None'}")
            details.label(text=f"Create Time:  {getattr(scene, 'hi3d_selected_texture_task_create_time', '') or 'None'}")
            image_box = layout.box()
            image_box.label(text="Texture Image")
            image_box.template_ID_preview(scene, "hi3d_texture_image", open="hi3d.load_texture_image")
            action = layout.row(align=True)
            is_generating_tex = getattr(scene, "hi3d_is_generating_texture", False)
            if is_generating_tex:
                tex_text = "Generating..."
            else:
                tex_text = "Generate (cost:{})".format(getattr(scene, "hi3d_texture_cost", 0))
            action.enabled = not is_generating_tex
            action.operator("hi3d.generate_texture", text=tex_text)

class HI3D_UL_task_list(bpy.types.UIList):
    def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
        row = layout.row(align=True)
        id_text = (item.task_id[:12] + "...") if item.task_id and len(item.task_id) > 12 else (item.task_id or "-")
        row.label(text=id_text)
        r = row.row(align=True)
        r.enabled = False
        r.prop(item, "gen_status", text="")
class HI3D_UL_texture_task_list(bpy.types.UIList):
    def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
        row = layout.row(align=True)
        id_text = (item.task_id[:12] + "...") if item.task_id and len(item.task_id) > 12 else (item.task_id or "-")
        row.label(text=id_text)
        r = row.row(align=True)
        r.enabled = False
        r.prop(item, "tex_status", text="")
classes = (
    VIEW3D_PT_hi3d_model_manager,
    VIEW3D_PT_hi3d_model_generator,
    VIEW3D_PT_hi3d_texture_generator,
    HI3D_UL_task_list,
    HI3D_UL_texture_task_list,
)


def register():
    for cls in classes:
        bpy.utils.register_class(cls)


def unregister():
    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)
