"""
NEXIUM Desktop Todo App - Complete Example
A beautiful desktop todo application built with NEXIUM

Requirements:
    pip install nexium[desktop]
"""

from nexium import Nexium, Model, HTMLResponse
from nexium.desktop import run_as_desktop

# Create app
app = Nexium(
    title="NEXIUM Todo",
    version="1.0.0",
    description="Beautiful desktop todo app",
    debug=False,
)


# Models
class Todo(Model):
    """Todo model."""
    __table__ = "todos"


# HTML Template (in production, use VIEWIX template engine)
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NEXIUM Todo</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 600px;
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 2.5em;
        }
        
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 0.9em;
        }
        
        .input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
        }
        
        input[type="text"] {
            flex: 1;
            padding: 15px 20px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s;
        }
        
        input[type="text"]:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        button {
            padding: 15px 30px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        button:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }
        
        button:active {
            transform: translateY(0);
        }
        
        .todo-list {
            list-style: none;
        }
        
        .todo-item {
            background: #f8f9fa;
            padding: 20px;
            margin-bottom: 10px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            gap: 15px;
            transition: all 0.3s;
            cursor: pointer;
        }
        
        .todo-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }
        
        .todo-item.completed {
            opacity: 0.6;
        }
        
        .todo-item.completed .todo-text {
            text-decoration: line-through;
        }
        
        .checkbox {
            width: 24px;
            height: 24px;
            border: 2px solid #667eea;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .checkbox.checked {
            background: #667eea;
        }
        
        .checkbox.checked::after {
            content: '✓';
            color: white;
            font-weight: bold;
        }
        
        .todo-text {
            flex: 1;
            font-size: 16px;
            color: #333;
        }
        
        .delete-btn {
            padding: 8px 16px;
            background: #dc3545;
            font-size: 14px;
        }
        
        .delete-btn:hover {
            background: #c82333;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }
        
        .empty-state-icon {
            font-size: 4em;
            margin-bottom: 20px;
        }
        
        .stats {
            display: flex;
            justify-content: space-around;
            margin-top: 30px;
            padding-top: 30px;
            border-top: 2px solid #e0e0e0;
        }
        
        .stat {
            text-align: center;
        }
        
        .stat-value {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-label {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>📝 NEXIUM Todo</h1>
        <p class="subtitle">Desktop app powered by NEXIUM framework</p>
        
        <div class="input-group">
            <input type="text" id="todoInput" placeholder="What needs to be done?" />
            <button onclick="addTodo()">Add Todo</button>
        </div>
        
        <ul class="todo-list" id="todoList">
            <!-- Todos will be loaded here -->
        </ul>
        
        <div class="stats">
            <div class="stat">
                <div class="stat-value" id="totalCount">0</div>
                <div class="stat-label">Total</div>
            </div>
            <div class="stat">
                <div class="stat-value" id="activeCount">0</div>
                <div class="stat-label">Active</div>
            </div>
            <div class="stat">
                <div class="stat-value" id="completedCount">0</div>
                <div class="stat-label">Completed</div>
            </div>
        </div>
    </div>
    
    <script>
        // Load todos on page load
        window.addEventListener('DOMContentLoaded', loadTodos);
        
        async function loadTodos() {
            const response = await fetch('/todos');
            const data = await response.json();
            renderTodos(data.todos);
        }
        
        async function addTodo() {
            const input = document.getElementById('todoInput');
            const text = input.value.trim();
            
            if (!text) return;
            
            const response = await fetch('/todos', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({text: text})
            });
            
            if (response.ok) {
                input.value = '';
                loadTodos();
            }
        }
        
        async function toggleTodo(id, completed) {
            await fetch(`/todos/${id}`, {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({completed: !completed})
            });
            loadTodos();
        }
        
        async function deleteTodo(id) {
            await fetch(`/todos/${id}`, {method: 'DELETE'});
            loadTodos();
        }
        
        function renderTodos(todos) {
            const list = document.getElementById('todoList');
            
            if (todos.length === 0) {
                list.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">🎉</div>
                        <p>No todos yet. Add one above!</p>
                    </div>
                `;
                updateStats(0, 0, 0);
                return;
            }
            
            let total = todos.length;
            let completed = todos.filter(t => t.completed).length;
            let active = total - completed;
            
            list.innerHTML = todos.map(todo => `
                <li class="todo-item ${todo.completed ? 'completed' : ''}" 
                    onclick="toggleTodo(${todo.id}, ${todo.completed})">
                    <div class="checkbox ${todo.completed ? 'checked' : ''}"></div>
                    <div class="todo-text">${todo.text}</div>
                    <button class="delete-btn" onclick="event.stopPropagation(); deleteTodo(${todo.id})">
                        Delete
                    </button>
                </li>
            `).join('');
            
            updateStats(total, active, completed);
        }
        
        function updateStats(total, active, completed) {
            document.getElementById('totalCount').textContent = total;
            document.getElementById('activeCount').textContent = active;
            document.getElementById('completedCount').textContent = completed;
        }
        
        // Allow Enter key to add todo
        document.getElementById('todoInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') addTodo();
        });
    </script>
</body>
</html>
"""


# Routes
@app.get("/")
async def home():
    """Serve the todo app UI."""
    return HTMLResponse(HTML_TEMPLATE)


@app.get("/todos")
async def list_todos():
    """List all todos."""
    todos = await Todo.all()
    return {"todos": [t.dict() for t in todos]}


@app.post("/todos")
async def create_todo(text: str):
    """Create a new todo."""
    todo = Todo(text=text, completed=False)
    await todo.save()
    return {"message": "Todo created", "todo": todo.dict()}


@app.put("/todos/{id}")
async def update_todo(id: int, completed: bool):
    """Update todo completion status."""
    todo = await Todo.get(id=id)
    if not todo:
        return {"error": "Todo not found"}, 404
    
    todo.completed = completed
    await todo.save()
    return {"message": "Todo updated", "todo": todo.dict()}


@app.delete("/todos/{id}")
async def delete_todo(id: int):
    """Delete a todo."""
    todo = await Todo.get(id=id)
    if not todo:
        return {"error": "Todo not found"}, 404
    
    await todo.delete()
    return {"message": "Todo deleted"}


if __name__ == "__main__":
    print("""
╔══════════════════════════════════════════════════════════╗
║                                                          ║
║  📝 NEXIUM TODO - Desktop Application                   ║
║                                                          ║
║  A beautiful todo app built with NEXIUM framework       ║
║  Running as native desktop application                  ║
║                                                          ║
╚══════════════════════════════════════════════════════════╝

🚀 Features:
   ✅ Native desktop window
   ✅ Beautiful modern UI
   ✅ Full CRUD operations
   ✅ Real-time updates
   ✅ Statistics dashboard

🖥️  Starting desktop app...
    """)
    
    # Run as desktop app
    run_as_desktop(
        app,
        title="NEXIUM Todo",
        width=650,
        height=800,
        resizable=True,
        min_size=(500, 600),
    )
