//! Theme selector screen with live preview
//!
//! Allows users to browse and preview available themes

// Note: This is a binary module
use crate::app::App;
use crate::theme::AppTheme;
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, Paragraph},
    Frame,
};

/// Theme option metadata
#[derive(Debug, Clone)]
pub(crate) struct ThemeOption {
    /// Theme name
    pub name: &'static str,
    /// Description
    pub description: &'static str,
    /// Primary color (for preview, reserved for future use)
    #[allow(dead_code)]
    pub primary_color: Color,
}

/// Get all available themes
pub(crate) fn get_available_themes() -> Vec<ThemeOption> {
    vec![
        ThemeOption {
            name: "default",
            description: "Professional cyan theme (recommended)",
            primary_color: Color::Cyan,
        },
        ThemeOption {
            name: "dark",
            description: "Dark mode with muted colors",
            primary_color: Color::Blue,
        },
        ThemeOption {
            name: "light",
            description: "Light mode with bright colors",
            primary_color: Color::LightCyan,
        },
        ThemeOption {
            name: "minimal",
            description: "High contrast white theme",
            primary_color: Color::White,
        },
        ThemeOption {
            name: "professional",
            description: "Corporate blue theme",
            primary_color: Color::LightBlue,
        },
    ]
}

/// Render theme selector screen
pub(crate) fn render_theme_selector(f: &mut Frame<'_>, app: &App, area: Rect, theme: &AppTheme) {
    // Create layout
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),      // Header
            Constraint::Percentage(60), // Theme list
            Constraint::Percentage(40), // Preview
        ])
        .split(area);

    // Render header
    let header = Paragraph::new(vec![Line::from(vec![Span::styled(
        "🎨 Theme Selector",
        theme.header_style(),
    )])])
    .block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme.border_style()),
    )
    .alignment(Alignment::Center);
    f.render_widget(header, chunks[0]);

    // Get themes
    let themes = get_available_themes();

    // Build theme list items
    let items: Vec<ListItem<'_>> = themes
        .iter()
        .enumerate()
        .map(|(i, t)| {
            let is_selected = i == app.theme_selector_index;
            let is_current = app.current_theme == t.name;

            let mut spans = vec![
                Span::raw("  "),
                Span::styled(
                    if is_selected { "▶ " } else { "  " },
                    Style::default().fg(theme.base.primary),
                ),
            ];

            // Theme name
            let name_style = if is_current {
                Style::default()
                    .fg(theme.base.success_color())
                    .add_modifier(Modifier::BOLD)
            } else if is_selected {
                theme.selected_item_style()
            } else {
                theme.list_item_style()
            };

            spans.push(Span::styled(format!("{:15}", t.name), name_style));

            // Current indicator
            if is_current {
                spans.push(Span::styled(" ✓ ", theme.success_style()));
            } else {
                spans.push(Span::raw("   "));
            }

            // Description
            spans.push(Span::styled(
                t.description,
                if is_selected {
                    theme.list_item_style()
                } else {
                    theme.metadata_style()
                },
            ));

            ListItem::new(Line::from(spans))
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme.border_style())
            .title(" Available Themes "),
    );
    f.render_widget(list, chunks[1]);

    // Render preview section
    let preview_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(33), Constraint::Percentage(67)])
        .split(chunks[2]);

    // Preview: Color swatches
    let selected_theme = &themes[app.theme_selector_index];
    let preview_theme = match selected_theme.name {
        "dark" => AppTheme::dark(),
        "light" => AppTheme::light(),
        "minimal" => AppTheme::minimal(),
        "professional" => AppTheme::professional(),
        _ => AppTheme::default_theme(),
    };

    let swatch_lines = vec![
        Line::from(vec![
            Span::raw("Primary:   "),
            Span::styled("████", Style::default().fg(preview_theme.base.primary)),
        ]),
        Line::from(vec![
            Span::raw("Success:   "),
            Span::styled(
                "████",
                Style::default().fg(preview_theme.base.success_color()),
            ),
        ]),
        Line::from(vec![
            Span::raw("Warning:   "),
            Span::styled(
                "████",
                Style::default().fg(preview_theme.base.warning_color()),
            ),
        ]),
        Line::from(vec![
            Span::raw("Error:     "),
            Span::styled(
                "████",
                Style::default().fg(preview_theme.base.error_color()),
            ),
        ]),
    ];

    let swatch_widget = Paragraph::new(swatch_lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(theme.border_style())
                .title(" Color Preview "),
        )
        .alignment(Alignment::Left);
    f.render_widget(swatch_widget, preview_chunks[0]);

    // Preview: Sample UI
    let sample_lines = vec![
        Line::from(vec![Span::styled(
            "Sample Header",
            preview_theme.header_style(),
        )]),
        Line::from(""),
        Line::from(vec![
            Span::styled("✓ ", preview_theme.success_style()),
            Span::styled("Completed task", preview_theme.list_item_style()),
        ]),
        Line::from(vec![
            Span::styled("○ ", preview_theme.metadata_style()),
            Span::styled("Pending task", preview_theme.list_item_style()),
        ]),
        Line::from(vec![
            Span::styled("▶ ", Style::default().fg(preview_theme.base.primary)),
            Span::styled("Selected item", preview_theme.selected_item_style()),
        ]),
    ];

    let sample_widget = Paragraph::new(sample_lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(preview_theme.border_style())
                .title(" UI Preview "),
        )
        .alignment(Alignment::Left);
    f.render_widget(sample_widget, preview_chunks[1]);

    // Footer instructions (overlay at bottom)
    let footer_area = Rect {
        x: area.x,
        y: area.y + area.height.saturating_sub(3),
        width: area.width,
        height: 3,
    };

    let footer = Paragraph::new(vec![Line::from(vec![
        Span::styled("↑/↓", theme.success_style().add_modifier(Modifier::BOLD)),
        Span::raw(" Navigate  "),
        Span::styled("Enter", theme.success_style().add_modifier(Modifier::BOLD)),
        Span::raw(" Apply  "),
        Span::styled("Esc", theme.warning_style().add_modifier(Modifier::BOLD)),
        Span::raw(" Cancel  "),
        Span::styled(
            "Ctrl+D",
            theme.metadata_style().add_modifier(Modifier::BOLD),
        ),
        Span::raw(" Toggle Dark"),
    ])])
    .block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme.border_style()),
    )
    .alignment(Alignment::Center);
    f.render_widget(footer, footer_area);
}

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

    #[test]
    fn test_available_themes() {
        let themes = get_available_themes();
        assert_eq!(themes.len(), 5);

        // Verify all expected themes exist
        assert!(themes.iter().any(|t| t.name == "default"));
        assert!(themes.iter().any(|t| t.name == "dark"));
        assert!(themes.iter().any(|t| t.name == "light"));
        assert!(themes.iter().any(|t| t.name == "minimal"));
        assert!(themes.iter().any(|t| t.name == "professional"));
    }

    #[test]
    fn test_theme_option_structure() {
        let themes = get_available_themes();

        for theme in themes {
            assert!(!theme.name.is_empty());
            assert!(!theme.description.is_empty());
        }
    }
}
