use crate::app::AppState;
/// Settings Screen
/// Configure system settings, AI providers, and mode
use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};

// === 4RUNR BRAND COLORS (matching layout.rs) ===
const BRAND_PURPLE: Color = Color::Rgb(138, 43, 226);
const CYBER_CYAN: Color = Color::Rgb(0, 255, 255);
const NEON_GREEN: Color = Color::Rgb(57, 255, 20);
const AMBER_WARN: Color = Color::Rgb(255, 191, 0);
const TEXT_PRIMARY: Color = Color::Rgb(230, 230, 240);
const TEXT_DIM: Color = Color::Rgb(100, 100, 120);
const TEXT_MUTED: Color = Color::Rgb(60, 60, 80);
const BG_PANEL: Color = Color::Rgb(18, 18, 25);

/// Settings state
#[derive(Debug, Clone)]
pub struct SettingsState {
    /// Current focused section
    pub focused_section: SettingsSection,

    /// Mode: Local or Connected
    pub mode: OperationMode,

    /// AI Provider settings
    pub ai_provider: String, // "openai", "anthropic", "local"
    pub ai_model: String,  // "gpt-4", "claude-3", etc.
    pub api_key_set: bool, // Whether API key is configured

    /// Gateway settings
    pub gateway_url: String,
    pub gateway_connected: bool,

    /// Auto-update setting
    pub auto_update: bool,

    /// Unsaved changes
    pub has_changes: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum SettingsSection {
    Mode,
    AIProvider,
    Gateway,
    AutoUpdate,
}

#[derive(Debug, Clone, PartialEq)]
pub enum OperationMode {
    Local,     // Local-only, no gateway
    Connected, // Connected to gateway
}

impl OperationMode {
    pub fn as_str(&self) -> &str {
        match self {
            OperationMode::Local => "Local",
            OperationMode::Connected => "Connected",
        }
    }

    pub fn description(&self) -> &str {
        match self {
            OperationMode::Local => "Offline mode - local tools and models only",
            OperationMode::Connected => {
                "Full mode - gateway access, server tools, Shield, Sentinel"
            }
        }
    }
}

impl Default for SettingsState {
    fn default() -> Self {
        Self {
            focused_section: SettingsSection::Mode,
            mode: OperationMode::Local,
            ai_provider: "openai".to_string(),
            ai_model: "gpt-4".to_string(),
            api_key_set: false,
            gateway_url: "http://localhost:3001".to_string(),
            gateway_connected: false,
            auto_update: true,
            has_changes: false,
        }
    }
}

impl SettingsState {
    /// Toggle mode
    pub fn toggle_mode(&mut self) {
        self.mode = match self.mode {
            OperationMode::Local => OperationMode::Connected,
            OperationMode::Connected => OperationMode::Local,
        };
        self.has_changes = true;
    }

    /// Cycle to next AI provider
    pub fn next_provider(&mut self) {
        self.ai_provider = match self.ai_provider.as_str() {
            "openai" => "anthropic".to_string(),
            "anthropic" => "local".to_string(),
            _ => "openai".to_string(),
        };

        // Update default model for provider
        self.ai_model = match self.ai_provider.as_str() {
            "openai" => "gpt-4".to_string(),
            "anthropic" => "claude-3-opus".to_string(),
            "local" => "llama2".to_string(),
            _ => "gpt-4".to_string(),
        };

        self.has_changes = true;
    }

    /// Toggle auto-update
    pub fn toggle_auto_update(&mut self) {
        self.auto_update = !self.auto_update;
        self.has_changes = true;
    }

    /// Move to next section
    pub fn next_section(&mut self) {
        self.focused_section = match self.focused_section {
            SettingsSection::Mode => SettingsSection::AIProvider,
            SettingsSection::AIProvider => SettingsSection::Gateway,
            SettingsSection::Gateway => SettingsSection::AutoUpdate,
            SettingsSection::AutoUpdate => SettingsSection::Mode,
        };
    }

    /// Move to previous section
    pub fn prev_section(&mut self) {
        self.focused_section = match self.focused_section {
            SettingsSection::Mode => SettingsSection::AutoUpdate,
            SettingsSection::AIProvider => SettingsSection::Mode,
            SettingsSection::Gateway => SettingsSection::AIProvider,
            SettingsSection::AutoUpdate => SettingsSection::Gateway,
        };
    }

    /// Save settings
    pub fn save(&mut self) {
        self.has_changes = false;
        // TODO: Persist settings to config file
    }

    /// Discard changes
    pub fn discard(&mut self) {
        // TODO: Reload from config file
        self.has_changes = false;
    }
}

/// Render the Settings screen
pub fn render(f: &mut Frame, state: &AppState) {
    let area = f.size();

    // Get settings state from AppState
    let settings = &state.settings;

    // Split screen into sections
    use ratatui::layout::{Constraint, Direction, Layout};

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(15),   // Settings content
            Constraint::Length(3), // Actions
        ])
        .split(area);

    render_header(f, chunks[0], settings);
    render_settings_content(f, chunks[1], settings);
    render_actions(f, chunks[2], settings);
}

fn render_header(f: &mut Frame, area: Rect, settings: &SettingsState) {
    let title = if settings.has_changes {
        " ⚙️  Settings (Unsaved Changes ●) "
    } else {
        " ⚙️  Settings "
    };

    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(Style::default().fg(if settings.has_changes {
            AMBER_WARN
        } else {
            BRAND_PURPLE
        }))
        .style(Style::default().bg(BG_PANEL));

    f.render_widget(block, area);
}

fn render_settings_content(f: &mut Frame, area: Rect, settings: &SettingsState) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(CYBER_CYAN))
        .style(Style::default().bg(BG_PANEL));

    let inner = block.inner(area);
    f.render_widget(block, area);

    let is_mode_focused = settings.focused_section == SettingsSection::Mode;
    let is_provider_focused = settings.focused_section == SettingsSection::AIProvider;
    let is_gateway_focused = settings.focused_section == SettingsSection::Gateway;
    let is_autoupdate_focused = settings.focused_section == SettingsSection::AutoUpdate;

    let text = vec![
        Line::from(""),
        // Mode Section
        Line::from(vec![
            Span::styled(
                if is_mode_focused { "▶ " } else { "  " },
                Style::default().fg(BRAND_PURPLE).bold(),
            ),
            Span::styled(
                "🌐 Operation Mode",
                Style::default().fg(TEXT_PRIMARY).bold(),
            ),
        ]),
        Line::from(vec![
            Span::raw("    "),
            Span::styled(
                format!(
                    "[{}] Local    [{}] Connected",
                    if settings.mode == OperationMode::Local {
                        "●"
                    } else {
                        " "
                    },
                    if settings.mode == OperationMode::Connected {
                        "●"
                    } else {
                        " "
                    }
                ),
                Style::default().fg(if is_mode_focused {
                    CYBER_CYAN
                } else {
                    TEXT_PRIMARY
                }),
            ),
        ]),
        Line::from(vec![
            Span::raw("    "),
            Span::styled(
                settings.mode.description(),
                Style::default().fg(TEXT_DIM).italic(),
            ),
        ]),
        Line::from(""),
        // AI Provider Section
        Line::from(vec![
            Span::styled(
                if is_provider_focused { "▶ " } else { "  " },
                Style::default().fg(BRAND_PURPLE).bold(),
            ),
            Span::styled("🤖 AI Provider", Style::default().fg(TEXT_PRIMARY).bold()),
        ]),
        Line::from(vec![
            Span::styled("    Provider: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                &settings.ai_provider,
                Style::default()
                    .fg(if is_provider_focused {
                        CYBER_CYAN
                    } else {
                        TEXT_PRIMARY
                    })
                    .bold(),
            ),
        ]),
        Line::from(vec![
            Span::styled("    Model: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                &settings.ai_model,
                Style::default().fg(if is_provider_focused {
                    CYBER_CYAN
                } else {
                    TEXT_PRIMARY
                }),
            ),
        ]),
        Line::from(vec![
            Span::styled("    API Key: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                if settings.api_key_set {
                    "Configured ✓"
                } else {
                    "Not set"
                },
                Style::default().fg(if settings.api_key_set {
                    NEON_GREEN
                } else {
                    Color::Rgb(255, 69, 69)
                }),
            ),
        ]),
        Line::from(""),
        // Gateway Section
        Line::from(vec![
            Span::styled(
                if is_gateway_focused { "▶ " } else { "  " },
                Style::default().fg(BRAND_PURPLE).bold(),
            ),
            Span::styled(
                "🔗 Gateway Connection",
                Style::default().fg(TEXT_PRIMARY).bold(),
            ),
        ]),
        Line::from(vec![
            Span::styled("    URL: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                &settings.gateway_url,
                Style::default().fg(if is_gateway_focused {
                    CYBER_CYAN
                } else {
                    TEXT_PRIMARY
                }),
            ),
        ]),
        Line::from(vec![
            Span::styled("    Status: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                if settings.gateway_connected {
                    "Connected ✓"
                } else {
                    "Disconnected"
                },
                Style::default().fg(if settings.gateway_connected {
                    NEON_GREEN
                } else {
                    TEXT_MUTED
                }),
            ),
        ]),
        Line::from(""),
        // Auto-update Section
        Line::from(vec![
            Span::styled(
                if is_autoupdate_focused { "▶ " } else { "  " },
                Style::default().fg(BRAND_PURPLE).bold(),
            ),
            Span::styled("🔄 Auto-Update", Style::default().fg(TEXT_PRIMARY).bold()),
        ]),
        Line::from(vec![
            Span::raw("    "),
            Span::styled(
                format!(
                    "[{}] Enable automatic updates",
                    if settings.auto_update { "✓" } else { " " }
                ),
                Style::default().fg(if is_autoupdate_focused {
                    CYBER_CYAN
                } else {
                    TEXT_PRIMARY
                }),
            ),
        ]),
    ];

    let paragraph = Paragraph::new(text)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(paragraph, inner);
}

fn render_actions(f: &mut Frame, area: Rect, settings: &SettingsState) {
    let block = Block::default()
        .title(" ⌨️  Actions ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(TEXT_DIM))
        .style(Style::default().bg(BG_PANEL));

    let inner = block.inner(area);
    f.render_widget(block, area);

    let text = if settings.has_changes {
        Line::from(vec![
            Span::styled("↑/↓", Style::default().fg(CYBER_CYAN).bold()),
            Span::styled(" Navigate  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Space", Style::default().fg(AMBER_WARN).bold()),
            Span::styled(" Toggle  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Enter", Style::default().fg(NEON_GREEN).bold()),
            Span::styled(" Save  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("ESC", Style::default().fg(Color::Rgb(255, 69, 69)).bold()),
            Span::styled(" Discard & Close", Style::default().fg(TEXT_DIM)),
        ])
    } else {
        Line::from(vec![
            Span::styled("↑/↓", Style::default().fg(CYBER_CYAN).bold()),
            Span::styled(" Navigate  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Space", Style::default().fg(AMBER_WARN).bold()),
            Span::styled(" Toggle  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("ESC", Style::default().fg(BRAND_PURPLE).bold()),
            Span::styled(" Close", Style::default().fg(TEXT_DIM)),
        ])
    };

    let paragraph = Paragraph::new(text)
        .style(Style::default().fg(TEXT_PRIMARY))
        .alignment(Alignment::Center);

    f.render_widget(paragraph, inner);
}
