import bpy
from bpy.types import Operator
from bpy.props import StringProperty
from ..utils.constants import is_full_version


class TEXT_TEXTURE_OT_edit_text(Operator):
    """Open a text editor for text input"""
    bl_idname = "text_texture.edit_text"
    bl_label = "Edit Text"
    bl_description = "Open a text editor for text input"
    bl_options = {'REGISTER', 'UNDO'}
    
    temp_text: StringProperty(
        name="Text",
        description="Text input",
        default="",
        maxlen=4096
    )
    
    @classmethod
    def poll(cls, context):
        """Only available in PRO version"""
        return is_full_version()
    
    def invoke(self, context, event):
        """Copy current text to temp storage and open dialog"""
        props = context.scene.text_texture_props
        self.temp_text = props.text
        return context.window_manager.invoke_props_dialog(self, width=700)
    
    def draw(self, context):
        """Draw the dialog UI"""
        layout = self.layout
        
        max_chars = 4096
        current_chars = len(self.temp_text)
        
        col = layout.column()
        
        col.label(text="Edit Text:", icon='EDITMODE_HLT')
        
        text_row = col.row()
        text_row.scale_y = 2.0
        text_row.prop(self, "temp_text", text="")
        
        col.separator()
        stats_row = col.row()
        stats_row.label(text=f"📝 Characters: {current_chars}/{max_chars}", icon='FONT_DATA')
        
        if current_chars > max_chars:
            col.separator()
            warning_box = col.box()
            warning_box.alert = True
            warning_box.label(text=f"⚠ Exceeds character limit! Will be trimmed to {max_chars} chars", icon='ERROR')
    
    def execute(self, context):
        """Save temp text back to main property"""
        props = context.scene.text_texture_props
        
        max_chars = 4096
        text = self.temp_text[:max_chars]
        props.text = text
        
        return {'FINISHED'}


classes = (TEXT_TEXTURE_OT_edit_text,)


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


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