from ..renderer.html_generator import get_current_generator
from ..utils.state import _state_manager


class InputValue:
    def __init__(self, name: str, default=''):
        self.name = name
        self.value = _state_manager.get_form_data(name, default)
    
    def __str__(self):
        return str(self.value)
    
    def __repr__(self):
        return f"InputValue({self.name}={self.value})"


def input(label: str, placeholder: str = '', type: str = 'text', required: bool = False, key: str = None):
    """Render a text input field"""
    gen = get_current_generator()
    name = key or f"input_{gen.get_next_id()}"
    
    gen.add_element('input', {
        'label': label,
        'placeholder': placeholder,
        'type': type,
        'required': required,
        'name': name
    })
    
    return InputValue(name)


def textarea(label: str, placeholder: str = '', rows: int = 4, required: bool = False, key: str = None):
    """Render a textarea input"""
    gen = get_current_generator()
    name = key or f"textarea_{gen.get_next_id()}"
    
    gen.add_element('textarea', {
        'label': label,
        'placeholder': placeholder,
        'rows': rows,
        'required': required,
        'name': name
    })
    
    return InputValue(name)


def checkbox(label: str, value: bool = False, key: str = None):
    """Render a checkbox"""
    gen = get_current_generator()
    name = key or f"checkbox_{gen.get_next_id()}"
    
    from flask import session
    state_key = f'checkbox_{name}'
    
    form_value = _state_manager.get_form_data(name)
    if form_value is not None:
        checked = form_value == 'on'
        session[state_key] = checked
        session.modified = True
    else:
        checked = session.get(state_key, value)
    
    gen.add_element('checkbox', {
        'label': label,
        'checked': checked,
        'name': name
    })
    
    return checked


def select(label: str, options: list, key: str = None):
    """Render a select dropdown"""
    gen = get_current_generator()
    name = key or f"select_{gen.get_next_id()}"
    
    gen.add_element('select', {
        'label': label,
        'options': options,
        'name': name
    })
    
    return InputValue(name, options[0] if options else '')


def radio(label: str, options: list, key: str = None):
    """Render radio buttons"""
    gen = get_current_generator()
    name = key or f"radio_{gen.get_next_id()}"
    
    gen.add_element('radio', {
        'label': label,
        'options': options,
        'name': name
    })
    
    return InputValue(name, options[0] if options else '')
