"""
Example: Custom Form Layouts with Callable Fields

This demonstrates the new v0.9 API where BoundFields are callable,
allowing for WTForms-style field rendering with runtime configuration.
"""
from textual.app import App
from textual.containers import Horizontal, Vertical
from textual.widgets import Button, Label, Static
from textual_wtf import Form, FormLayout, StringField, IntegerField, BooleanField


# Example 1: Using the default layout (backward compatible)
class BasicForm(Form):
    """Form using default vertical layout"""
    name = StringField(label="Name", required=True)
    email = StringField(label="Email", required=True)
    age = IntegerField(label="Age", min_value=0, max_value=130)
    newsletter = BooleanField(label="Subscribe to newsletter")


# Example 2: Custom two-column layout
class TwoColumnLayout(FormLayout):
    """Custom layout with fields in two columns"""
    
    def compose_form(self):
        """Arrange fields in two columns with custom styling"""
        
        # Title
        yield Static("User Registration", id="custom-title")
        
        # Two-column field layout
        with Horizontal(id="form-columns"):
            with Vertical(id="left-column"):
                yield Label("Personal Info")
                # Call fields with custom kwargs
                yield self.form.name(placeholder="Enter your full name")
                yield self.form.age(placeholder="Your age")
            
            with Vertical(id="right-column"):
                yield Label("Contact")
                yield self.form.email(placeholder="you@example.com")
                yield self.form.newsletter()
        
        # Buttons
        with Horizontal(id="form-buttons"):
            yield Button("Cancel", id="cancel", variant="warning")
            yield Button("Submit", id="submit", variant="success")
    
    # Note: Button handlers are inherited from FormLayout
    # They post Form.Submitted and Form.Cancelled messages


# Example 3: Inline layout (fields on same row)
class InlineLayout(FormLayout):
    """Compact inline layout for quick forms"""
    
    def compose_form(self):
        """Single row layout"""
        with Horizontal(id="inline-form"):
            yield self.form.name(placeholder="Name")
            yield self.form.email(placeholder="Email")
            yield Button("Go", id="submit", variant="primary")


# Example 4: Stepped/wizard layout
class WizardLayout(FormLayout):
    """Multi-step form layout"""
    
    def compose_form(self):
        """Show fields in logical steps"""
        
        # Step 1: Basic Info
        with Vertical(classes="wizard-step"):
            yield Static("Step 1: Basic Information", classes="step-title")
            yield self.form.name(placeholder="Full name")
            yield self.form.age()
        
        # Step 2: Contact
        with Vertical(classes="wizard-step"):
            yield Static("Step 2: Contact Details", classes="step-title")
            yield self.form.email(placeholder="Email address")
            yield self.form.newsletter()
        
        # Navigation
        with Horizontal(id="wizard-nav"):
            yield Button("Previous", id="prev", disabled=True)
            yield Button("Next", id="next")
            yield Button("Submit", id="submit", variant="success")


# Example usage in an app
class CustomLayoutApp(App):
    """Demo app showing different layout options"""
    
    CSS = """
    #custom-title {
        background: $primary;
        color: $text;
        padding: 1;
        text-align: center;
    }
    
    #form-columns {
        margin: 1;
    }
    
    #left-column, #right-column {
        width: 1fr;
        padding: 0 2;
    }
    
    .wizard-step {
        margin: 1;
        padding: 1;
        border: solid $accent;
    }
    
    .step-title {
        background: $accent;
        padding: 1;
    }
    """
    
    def compose(self):
        # Choose which layout to use:
        
        # Option 1: Default layout (no layout_class specified)
        # form = BasicForm(title="Basic Form")
        
        # Option 2: Two-column layout
        form = BasicForm(layout_class=TwoColumnLayout)
        
        # Option 3: Inline layout
        # form = BasicForm(layout_class=InlineLayout)
        
        # Option 4: Wizard layout
        # form = BasicForm(layout_class=WizardLayout)
        
        yield form.render()
    
    def on_form_submitted(self, event: Form.Submitted):
        """Handle form submission"""
        data = event.layout.get_data()
        self.notify(f"Submitted: {data}", severity="information")
    
    def on_form_cancelled(self, event: Form.Cancelled):
        """Handle form cancellation"""
        self.notify("Form cancelled", severity="warning")


# Example 5: Programmatic field configuration
class DynamicForm(Form):
    """Form with fields configured at runtime"""
    username = StringField(label="Username")
    password = StringField(label="Password")


class DynamicLayout(FormLayout):
    """Layout that configures fields based on app state"""
    
    def __init__(self, form, read_only=False, **kwargs):
        super().__init__(form, **kwargs)
        self.read_only = read_only
    
    def compose_form(self):
        """Configure fields based on read_only state"""
        
        if self.read_only:
            # Read-only mode: disable all fields
            yield self.form.username(disabled=True)
            yield self.form.password(disabled=True, type="text")  # Show password
            yield Button("Edit", id="edit-button")
        else:
            # Edit mode: normal fields
            yield self.form.username(placeholder="Choose username")
            yield self.form.password(type="password", placeholder="Enter password")
            yield Button("Save", id="submit", variant="primary")
            yield Button("Cancel", id="cancel")


# Key features demonstrated:
# 
# 1. Callable fields: form.fieldname(**kwargs)
# 2. Runtime widget configuration via kwargs
# 3. Custom layout classes by subclassing FormLayout
# 4. Flexible composition: any Textual container structure
# 5. Button event handling via FormLayout base class
# 6. Backward compatibility with default layout
# 7. Dynamic field configuration based on app state


if __name__ == "__main__":
    app = CustomLayoutApp()
    app.run()
