#![forbid(unsafe_code)]

//! Web dashboard server
//!
//! Serves the Leptos web application on a configurable port (default 3001)
//!
//! Configuration hierarchy:
//! 1. .dashboard/config.toml file
//! 2. Environment variables (DASHBOARD_*, API_*)
//! 3. Built-in defaults

use axum::{
    response::{Html, IntoResponse},
    routing::get,
    Router,
};
use std::net::SocketAddr;
use syntaxis_dashboard::api;
use syntaxis_dashboard::components::filter_controls;
use syntaxis_dashboard::config::DashboardConfig;
use syntaxis_dashboard::filter::TaskSortOption;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;

#[tokio::main]
async fn main() {
    // Initialize tracing
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive(tracing_subscriber::filter::LevelFilter::INFO.into()),
        )
        .init();

    // Load configuration
    let config = DashboardConfig::load();
    config.log_config();

    // Configure API client with loaded config
    api::set_api_base(config.api.base_url.clone());

    // Create router
    let app = Router::new()
        .route("/", get(index))
        .layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()));

    let socket_addr = format!("{}:{}", config.server.host, config.server.port);
    let addr: SocketAddr = socket_addr.parse().expect("Invalid socket address");

    let listener = tokio::net::TcpListener::bind(&addr)
        .await
        .expect("Failed to bind");

    tracing::info!("Dashboard server listening on {}", addr);
    tracing::info!(
        "Open http://{}:{} in your browser",
        config.server.host,
        config.server.port
    );
    tracing::info!("API Server: {}", config.api.base_url);

    axum::serve(listener, app).await.expect("Server error");
}

/// HTML index page serving the Leptos app
///
/// Provides the main dashboard interface with task filtering and search capabilities.
/// In production, this would serve compiled WASM and proper SSR output.
async fn index() -> impl IntoResponse {
    let filter_html =
        filter_controls::filter_controls_html("", None, TaskSortOption::CreatedNewest);
    let stats_html = filter_controls::task_stats_html(0, 0, 0, 0.0);

    Html(format!(
        "<!DOCTYPE html>\n\
         <html lang=\"en\">\n\
         <head>\n\
             <meta charset=\"UTF-8\">\n\
             <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\
             <title>Lifecycle Dashboard - Task Management</title>\n\
             <script src=\"https://cdn.tailwindcss.com\"></script>\n\
             <style>\n\
                 body {{\n\
                     font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n\
                 }}\n\
                 .task-list {{\n\
                     max-height: 600px;\n\
                     overflow-y: auto;\n\
                 }}\n\
             </style>\n\
         </head>\n\
         <body class=\"bg-gray-50\">\n\
             <div class=\"min-h-screen\">\n\
                 <!-- Header -->\n\
                 <header class=\"bg-white shadow\">\n\
                     <div class=\"max-w-7xl mx-auto px-6 py-4\">\n\
                         <h1 class=\"text-3xl font-bold text-gray-900\">Syntaxis Dashboard</h1>\n\
                         <p class=\"text-gray-600 mt-1\">Manage tasks, track progress, and organize your projects</p>\n\
                     </div>\n\
                 </header>\n\
                 \n\
                 <!-- Main Content -->\n\
                 <main class=\"max-w-7xl mx-auto px-6 py-8\">\n\
                     <!-- Statistics -->\n\
                     {}\n\
                     \n\
                     <!-- Filter Controls -->\n\
                     {}\n\
                     \n\
                     <!-- Task List -->\n\
                     <div class=\"bg-white rounded-lg shadow-md\">\n\
                         <div class=\"p-6 border-b border-gray-200\">\n\
                             <h2 class=\"text-xl font-semibold text-gray-900\">Tasks</h2>\n\
                         </div>\n\
                         <div class=\"task-list p-6 space-y-3\">\n\
                             <p class=\"text-center text-gray-500 py-8\">\n\
                                 Loading tasks... If this doesn't load, ensure the API server is running on port 3000\n\
                             </p>\n\
                             <p class=\"text-center text-sm text-gray-400\">\n\
                                 API Server: <a href=\"http://localhost:3000/api/health\" class=\"text-blue-600 hover:underline\">http://localhost:3000</a>\n\
                             </p>\n\
                         </div>\n\
                     </div>\n\
                     \n\
                     <!-- Help & Documentation -->\n\
                     <div class=\"mt-8 bg-blue-50 rounded-lg shadow-sm p-6 border border-blue-200\">\n\
                         <h3 class=\"text-lg font-semibold text-blue-900 mb-3\">Filtering & Search</h3>\n\
                         <ul class=\"text-blue-800 space-y-2 text-sm\">\n\
                             <li><strong>Search:</strong> Type in the search box to find tasks by description or ID</li>\n\
                             <li><strong>Status Filter:</strong> Use buttons to show All Tasks, Completed, or Pending items</li>\n\
                             <li><strong>Sort Options:</strong> Organize tasks by date, priority, or completion status</li>\n\
                             <li><strong>Priority Levels:</strong> 🔴 Critical, 🟠 High, 🟡 Medium, 🟢 Low</li>\n\
                             <li><strong>Task Types:</strong> Feature (⭐), Bug Fix (🐛), Documentation (📚), Testing (✔), Deployment (🚀), Maintenance (🔧)</li>\n\
                         </ul>\n\
                     </div>\n\
                 </main>\n\
                 \n\
                 <!-- Footer -->\n\
                 <footer class=\"bg-gray-800 text-gray-300 mt-12\">\n\
                     <div class=\"max-w-7xl mx-auto px-6 py-6\">\n\
                         <p class=\"text-sm\">\n\
                             Syntaxis Dashboard v1.0 • \n\
                             <a href=\"#\" class=\"text-blue-400 hover:text-blue-300\">Documentation</a> • \n\
                             <a href=\"#\" class=\"text-blue-400 hover:text-blue-300\">Report Issue</a>\n\
                         </p>\n\
                     </div>\n\
                 </footer>\n\
             </div>\n\
         </body>\n\
         </html>",
        stats_html,
        filter_html
    ))
}
