//! Filter controls component for task filtering and searching
//!
//! Follows L-COMPONENT-PROPS and L-COMPONENT-REUSE patterns.
//! Provides search input, completion status filter, and sort options.

use crate::filter::TaskSortOption;

/// Generate filter controls HTML
///
/// Creates a controls panel with search input, filter buttons, and sort dropdown.
/// Allows users to:
/// - Search tasks by description or ID
/// - Filter by completion status (all/completed/pending)
/// - Sort by various criteria (newest, oldest, priority, etc.)
pub fn filter_controls_html(
    search_query: &str,
    filter_completed: Option<bool>,
    sort_option: TaskSortOption,
) -> String {
    let filter_all_class = if filter_completed.is_none() {
        "px-4 py-2 rounded-md text-sm font-medium text-white bg-blue-600"
    } else {
        "px-4 py-2 rounded-md text-sm font-medium text-gray-700 bg-white border border-gray-300 hover:bg-gray-50"
    };

    let filter_completed_class = if filter_completed == Some(true) {
        "px-4 py-2 rounded-md text-sm font-medium text-white bg-green-600"
    } else {
        "px-4 py-2 rounded-md text-sm font-medium text-gray-700 bg-white border border-gray-300 hover:bg-gray-50"
    };

    let filter_pending_class = if filter_completed == Some(false) {
        "px-4 py-2 rounded-md text-sm font-medium text-white bg-yellow-600"
    } else {
        "px-4 py-2 rounded-md text-sm font-medium text-gray-700 bg-white border border-gray-300 hover:bg-gray-50"
    };

    format!(
        r#"<div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <div class="space-y-4">
                <!-- Search Section -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Search Tasks</label>
                    <input type="text" placeholder="Search by description or task ID..."
                           value="{}"
                           class="w-full px-4 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500" />
                </div>

                <!-- Completion Status Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                    <div class="flex gap-2">
                        <button class="{} transition-colors" data-filter="all">All Tasks</button>
                        <button class="{} transition-colors" data-filter="completed">✓ Completed</button>
                        <button class="{} transition-colors" data-filter="pending">⏳ Pending</button>
                    </div>
                </div>

                <!-- Sort Options -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Sort By</label>
                    <select class="w-full px-4 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="newest" {}>Newest First</option>
                        <option value="oldest" {}>Oldest First</option>
                        <option value="priority_highest" {}>Highest Priority</option>
                        <option value="priority_lowest" {}>Lowest Priority</option>
                        <option value="completed_first" {}>Completed First</option>
                        <option value="pending_first" {}>Pending First</option>
                    </select>
                </div>
            </div>
        </div>"#,
        escape_html(search_query),
        filter_all_class,
        filter_completed_class,
        filter_pending_class,
        is_selected(sort_option, TaskSortOption::CreatedNewest),
        is_selected(sort_option, TaskSortOption::CreatedOldest),
        is_selected(sort_option, TaskSortOption::PriorityHighest),
        is_selected(sort_option, TaskSortOption::PriorityLowest),
        is_selected(sort_option, TaskSortOption::CompletedFirst),
        is_selected(sort_option, TaskSortOption::PendingFirst),
    )
}

/// Generate task list item HTML with priority and type badges
///
/// Creates a list item showing task information with visual indicators for
/// priority level and task type.
pub fn task_item_html(
    id: &str,
    description: &str,
    completed: bool,
    priority: &str,
    task_type: &str,
) -> String {
    let priority_color = match priority {
        "critical" => "text-red-600 bg-red-50",
        "high" => "text-orange-600 bg-orange-50",
        "medium" => "text-yellow-600 bg-yellow-50",
        "low" => "text-green-600 bg-green-50",
        _ => "text-gray-600 bg-gray-50",
    };

    let type_icon = match task_type {
        "feature" => "⭐",
        "bugfix" => "🐛",
        "documentation" => "📚",
        "testing" => "✔",
        "deployment" => "🚀",
        "maintenance" => "🔧",
        _ => "📋",
    };

    let completed_class = if completed {
        "line-through text-gray-400"
    } else {
        "text-gray-900"
    };

    format!(
        r#"<div class="bg-white rounded-lg shadow-sm p-4 flex items-center justify-between hover:shadow-md transition-shadow">
            <div class="flex items-start flex-1">
                <input type="checkbox" {} class="mt-1 mr-4" />
                <div class="flex-1">
                    <p class="font-medium {}">{}</p>
                    <p class="text-sm text-gray-500">ID: {}</p>
                    <div class="flex gap-2 mt-2">
                        <span class="inline-block px-2 py-1 rounded-md text-xs font-medium {}">
                            {}: {}
                        </span>
                        <span class="inline-block px-2 py-1 rounded-md text-xs font-medium text-blue-600 bg-blue-50">
                            {} {}
                        </span>
                    </div>
                </div>
            </div>
        </div>"#,
        if completed { "checked" } else { "" },
        completed_class,
        escape_html(description),
        escape_html(id),
        priority_color,
        capitalize(priority),
        capitalize(priority),
        type_icon,
        capitalize(task_type),
    )
}

/// Generate task statistics summary
///
/// Shows overall task completion percentage and counts.
pub fn task_stats_html(
    total: usize,
    completed: usize,
    pending: usize,
    completion_percentage: f64,
) -> String {
    format!(
        r#"<div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <div class="grid grid-cols-4 gap-4">
                <div class="text-center">
                    <p class="text-gray-600 text-sm">Total Tasks</p>
                    <p class="text-2xl font-bold text-gray-900">{}</p>
                </div>
                <div class="text-center">
                    <p class="text-gray-600 text-sm">Completed</p>
                    <p class="text-2xl font-bold text-green-600">{}</p>
                </div>
                <div class="text-center">
                    <p class="text-gray-600 text-sm">Pending</p>
                    <p class="text-2xl font-bold text-yellow-600">{}</p>
                </div>
                <div class="text-center">
                    <p class="text-gray-600 text-sm">Completion</p>
                    <p class="text-2xl font-bold text-blue-600">{:.1}%</p>
                </div>
            </div>
            <div class="mt-4 bg-gray-200 rounded-full h-2">
                <div class="bg-green-600 h-2 rounded-full transition-all" style="width: {:.1}%"></div>
            </div>
        </div>"#,
        total, completed, pending, completion_percentage, completion_percentage
    )
}

/// Escape HTML special characters
fn escape_html(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

/// Capitalize first letter of string
fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

/// Check if sort option matches
fn is_selected(current: TaskSortOption, check: TaskSortOption) -> &'static str {
    if current == check {
        "selected"
    } else {
        ""
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_filter_controls_html_generation() {
        let html = filter_controls_html("test query", None, TaskSortOption::CreatedNewest);
        assert!(html.contains("test query"));
        assert!(html.contains("Search Tasks"));
        assert!(html.contains("Status"));
        assert!(html.contains("Sort By"));
    }

    #[test]
    fn test_task_item_html_generation() {
        let html = task_item_html("task-1", "Implement feature", false, "high", "feature");
        assert!(html.contains("Implement feature"));
        assert!(html.contains("task-1"));
        assert!(html.contains("High")); // Capitalized by capitalize() function
        assert!(html.contains("Feature"));
    }

    #[test]
    fn test_task_item_completed_state() {
        let html = task_item_html("task-1", "Complete task", true, "medium", "bugfix");
        assert!(html.contains("checked"));
        assert!(html.contains("line-through"));
    }

    #[test]
    fn test_html_escaping() {
        let html = filter_controls_html(
            "<script>alert('xss')</script>",
            None,
            TaskSortOption::CreatedNewest,
        );
        assert!(!html.contains("<script>"));
        assert!(html.contains("&lt;script&gt;"));
    }

    #[test]
    fn test_task_stats_html() {
        let html = task_stats_html(10, 7, 3, 70.0);
        assert!(html.contains("10"));
        assert!(html.contains("7"));
        assert!(html.contains("3"));
        assert!(html.contains("70.0"));
    }
}
