use std::collections::HashSet;

use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};
use ratatui::Frame;

use crate::app::App;
use crate::engine::SequencerSnapshot;
use crate::model::SourceSpan;
use crate::state::MainLayout;
use crate::theme;
use crate::views::highlight::highlight_line_with_runtime;
use crate::views::render::{adjust_resolved_for_line, adjust_spans_for_line};
use crate::widgets::{ActivePatterns, Orientation, Scope, Spectrum, VuMeter};

pub fn layout(area: Rect) -> [Rect; 5] {
    Layout::horizontal([
        Constraint::Length(13),
        Constraint::Length(2),
        Constraint::Fill(1),
        Constraint::Length(2),
        Constraint::Length(10),
    ])
    .areas(area)
}

pub fn render(frame: &mut Frame, app: &App, snapshot: &SequencerSnapshot, area: Rect) {
    let [patterns_area, _, main_area, _, vu_area] = layout(area);

    let show_scope = app.audio.config.show_scope;
    let show_spectrum = app.audio.config.show_spectrum;
    let show_preview = app.audio.config.show_preview;
    let has_viz = show_scope || show_spectrum || show_preview;
    let layout = app.audio.config.layout;

    let (viz_area, sequencer_area) = match layout {
        MainLayout::Top => {
            let viz_height = if has_viz { 16 } else { 0 };
            let [viz, seq] = Layout::vertical([
                Constraint::Length(viz_height),
                Constraint::Fill(1),
            ])
            .areas(main_area);
            (viz, seq)
        }
        MainLayout::Bottom => {
            let viz_height = if has_viz { 16 } else { 0 };
            let [seq, viz] = Layout::vertical([
                Constraint::Fill(1),
                Constraint::Length(viz_height),
            ])
            .areas(main_area);
            (viz, seq)
        }
        MainLayout::Left => {
            let viz_width = if has_viz { 33 } else { 0 };
            let [viz, _spacer, seq] = Layout::horizontal([
                Constraint::Percentage(viz_width),
                Constraint::Length(2),
                Constraint::Fill(1),
            ])
            .areas(main_area);
            (viz, seq)
        }
        MainLayout::Right => {
            let viz_width = if has_viz { 33 } else { 0 };
            let [seq, _spacer, viz] = Layout::horizontal([
                Constraint::Fill(1),
                Constraint::Length(2),
                Constraint::Percentage(viz_width),
            ])
            .areas(main_area);
            (viz, seq)
        }
    };

    if has_viz {
        render_viz_area(frame, app, snapshot, viz_area);
    }

    render_sequencer(frame, app, snapshot, sequencer_area);
    render_vu_meter(frame, app, vu_area);
    render_active_patterns(frame, app, snapshot, patterns_area);
}

enum VizPanel {
    Scope,
    Spectrum,
    Preview,
}

fn render_viz_area(
    frame: &mut Frame,
    app: &App,
    snapshot: &SequencerSnapshot,
    area: Rect,
) {
    let is_vertical_layout = matches!(app.audio.config.layout, MainLayout::Left | MainLayout::Right);
    let show_scope = app.audio.config.show_scope;
    let show_spectrum = app.audio.config.show_spectrum;
    let show_preview = app.audio.config.show_preview;

    let mut panels = Vec::new();
    if show_scope { panels.push(VizPanel::Scope); }
    if show_spectrum { panels.push(VizPanel::Spectrum); }
    if show_preview { panels.push(VizPanel::Preview); }

    let constraints: Vec<Constraint> = panels.iter().map(|_| Constraint::Fill(1)).collect();

    let areas: Vec<Rect> = if is_vertical_layout {
        Layout::vertical(&constraints).split(area).to_vec()
    } else {
        Layout::horizontal(&constraints).split(area).to_vec()
    };

    let orientation = if is_vertical_layout {
        Orientation::Vertical
    } else {
        Orientation::Horizontal
    };

    for (panel, panel_area) in panels.iter().zip(areas.iter()) {
        match panel {
            VizPanel::Scope => render_scope(frame, app, *panel_area, orientation),
            VizPanel::Spectrum => render_spectrum(frame, app, *panel_area),
            VizPanel::Preview => render_script_preview(frame, app, snapshot, *panel_area),
        }
    }
}

const STEPS_PER_PAGE: usize = 32;

fn render_sequencer(frame: &mut Frame, app: &App, snapshot: &SequencerSnapshot, area: Rect) {
    let theme = theme::get();

    if area.width < 50 {
        let msg = Paragraph::new("Terminal too narrow")
            .alignment(Alignment::Center)
            .style(Style::new().fg(theme.ui.text_muted));
        frame.render_widget(msg, area);
        return;
    }

    let pattern = app.current_edit_pattern();
    let length = pattern.length;
    let page = app.editor_ctx.step / STEPS_PER_PAGE;
    let page_start = page * STEPS_PER_PAGE;
    let steps_on_page = (page_start + STEPS_PER_PAGE).min(length) - page_start;

    let num_rows = steps_on_page.div_ceil(8);
    let steps_per_row = steps_on_page.div_ceil(num_rows);

    let row_height = area.height / num_rows as u16;

    let row_constraints: Vec<Constraint> = (0..num_rows)
        .map(|_| Constraint::Length(row_height))
        .collect();
    let rows = Layout::vertical(row_constraints).split(area);

    for row_idx in 0..num_rows {
        let row_area = rows[row_idx];
        let start_step = row_idx * steps_per_row;
        let end_step = (start_step + steps_per_row).min(steps_on_page);
        let cols_in_row = end_step - start_step;

        let col_constraints: Vec<Constraint> = (0..cols_in_row * 2 - 1)
            .map(|i| {
                if i % 2 == 0 {
                    Constraint::Fill(1)
                } else if i == cols_in_row - 1 {
                    Constraint::Length(2)
                } else {
                    Constraint::Length(1)
                }
            })
            .collect();
        let cols = Layout::horizontal(col_constraints).split(row_area);

        for col_idx in 0..cols_in_row {
            let step_idx = page_start + start_step + col_idx;
            if step_idx < length {
                render_tile(frame, cols[col_idx * 2], app, snapshot, step_idx);
            }
        }
    }

}

fn render_tile(
    frame: &mut Frame,
    area: Rect,
    app: &App,
    snapshot: &SequencerSnapshot,
    step_idx: usize,
) {
    let theme = theme::get();
    let pattern = app.current_edit_pattern();
    let step = pattern.step(step_idx);
    let is_active = step.map(|s| s.active).unwrap_or(false);
    let has_content = step.map(|s| s.has_content()).unwrap_or(false);
    let is_linked = step.map(|s| s.source.is_some()).unwrap_or(false);
    let is_selected = step_idx == app.editor_ctx.step;
    let in_selection = app.editor_ctx.selection_range()
        .map(|r| r.contains(&step_idx))
        .unwrap_or(false);

    let is_playing = if app.playback.playing {
        snapshot.get_step(app.editor_ctx.bank, app.editor_ctx.pattern) == Some(step_idx)
    } else {
        false
    };

    let link_color = step.and_then(|s| s.source).map(|src| {
        let i = src as usize % 5;
        (theme.tile.link_bright[i], theme.tile.link_dim[i])
    });

    let (bg, fg) = match (is_playing, is_active, is_selected, is_linked, in_selection) {
        (true, true, _, _, _) => (theme.tile.playing_active_bg, theme.tile.playing_active_fg),
        (true, false, _, _, _) => (theme.tile.playing_inactive_bg, theme.tile.playing_inactive_fg),
        (false, true, true, true, _) => {
            let (r, g, b) = link_color.unwrap().0;
            (Color::Rgb(r, g, b), theme.selection.cursor_fg)
        }
        (false, true, true, false, _) => (theme.tile.active_selected_bg, theme.selection.cursor_fg),
        (false, true, _, _, true) => (theme.tile.active_in_range_bg, theme.selection.cursor_fg),
        (false, true, false, true, _) => {
            let (r, g, b) = link_color.unwrap().1;
            (Color::Rgb(r, g, b), theme.tile.active_fg)
        }
        (false, true, false, false, _) => {
            let bg = if has_content { theme.tile.content_bg } else { theme.tile.active_bg };
            (bg, theme.tile.active_fg)
        }
        (false, false, true, _, _) => (theme.selection.selected, theme.selection.cursor_fg),
        (false, false, _, _, true) => (theme.selection.in_range, theme.selection.cursor_fg),
        (false, false, false, _, _) => (theme.tile.inactive_bg, theme.tile.inactive_fg),
    };

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::new().fg(theme.ui.border));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let source_idx = step.and_then(|s| s.source);
    let symbol = if is_playing {
        "▶".to_string()
    } else if let Some(source) = source_idx {
        format!("→{:02}", source + 1)
    } else if has_content {
        format!("·{:02}·", step_idx + 1)
    } else {
        format!("{:02}", step_idx + 1)
    };

    // For linked steps, get the name from the source step
    let step_name = if let Some(src) = source_idx {
        pattern.step(src as usize).and_then(|s| s.name.as_ref())
    } else {
        step.and_then(|s| s.name.as_ref())
    };
    let num_lines = if step_name.is_some() { 2u16 } else { 1u16 };
    let content_height = num_lines;
    let y_offset = inner.height.saturating_sub(content_height) / 2;

    // Fill background for inner area
    let bg_fill = Paragraph::new("").style(Style::new().bg(bg));
    frame.render_widget(bg_fill, inner);

    if let Some(name) = step_name {
        let name_area = Rect {
            x: inner.x,
            y: inner.y + y_offset,
            width: inner.width,
            height: 1,
        };
        let name_widget = Paragraph::new(name.as_str())
            .alignment(Alignment::Center)
            .style(Style::new().bg(bg).fg(fg).add_modifier(Modifier::BOLD));
        frame.render_widget(name_widget, name_area);

        let symbol_area = Rect {
            x: inner.x,
            y: inner.y + y_offset + 1,
            width: inner.width,
            height: 1,
        };
        let symbol_widget = Paragraph::new(symbol)
            .alignment(Alignment::Center)
            .style(Style::new().bg(bg).fg(fg).add_modifier(Modifier::BOLD));
        frame.render_widget(symbol_widget, symbol_area);
    } else {
        let centered_area = Rect {
            x: inner.x,
            y: inner.y + y_offset,
            width: inner.width,
            height: 1,
        };
        let tile = Paragraph::new(symbol)
            .alignment(Alignment::Center)
            .style(Style::new().bg(bg).fg(fg).add_modifier(Modifier::BOLD));
        frame.render_widget(tile, centered_area);
    }
}

fn render_scope(frame: &mut Frame, app: &App, area: Rect, orientation: Orientation) {
    let theme = theme::get();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::new().fg(theme.ui.border));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let scope = Scope::new(&app.metrics.scope)
        .orientation(orientation)
        .color(theme.meter.low);
    frame.render_widget(scope, inner);
}

fn render_spectrum(frame: &mut Frame, app: &App, area: Rect) {
    let theme = theme::get();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::new().fg(theme.ui.border));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let spectrum = Spectrum::new(&app.metrics.spectrum);
    frame.render_widget(spectrum, inner);
}

fn render_script_preview(
    frame: &mut Frame,
    app: &App,
    snapshot: &SequencerSnapshot,
    area: Rect,
) {
    let theme = theme::get();
    let user_words: HashSet<String> = app.dict.lock().keys().cloned().collect();

    let pattern = app.current_edit_pattern();
    let step_idx = app.editor_ctx.step;
    let step = pattern.step(step_idx);
    let source_idx = step.and_then(|s| s.source);
    let step_name = step.and_then(|s| s.name.as_ref());

    let title = match (source_idx, step_name) {
        (Some(src), Some(name)) => format!(" {:02}: {} -> {:02} ", step_idx + 1, name, src + 1),
        (None, Some(name)) => format!(" {:02}: {} ", step_idx + 1, name),
        (Some(src), None) => format!(" {:02} -> {:02} ", step_idx + 1, src + 1),
        (None, None) => format!(" Step {:02} ", step_idx + 1),
    };

    let block = Block::default()
        .borders(Borders::ALL)
        .title(title)
        .border_style(Style::new().fg(theme.ui.border));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let script = pattern.resolve_script(step_idx).unwrap_or("");
    if script.is_empty() {
        let empty = Paragraph::new("(empty)")
            .alignment(Alignment::Center)
            .style(Style::new().fg(theme.ui.text_dim));
        let centered = Rect {
            y: inner.y + inner.height / 2,
            height: 1,
            ..inner
        };
        frame.render_widget(empty, centered);
        return;
    }

    let trace = if app.ui.runtime_highlight && app.playback.playing {
        let source = pattern.resolve_source(step_idx);
        snapshot.get_trace(app.editor_ctx.bank, app.editor_ctx.pattern, source)
    } else {
        None
    };

    let resolved_display: Vec<(SourceSpan, String)> = trace
        .map(|t| {
            t.resolved
                .iter()
                .map(|(s, v)| (*s, v.display()))
                .collect()
        })
        .unwrap_or_default();

    let mut line_start = 0usize;
    let lines: Vec<Line> = script
        .lines()
        .take(inner.height as usize)
        .map(|line_str| {
            let tokens = if let Some(t) = trace {
                let exec = adjust_spans_for_line(&t.executed_spans, line_start, line_str.len());
                let sel = adjust_spans_for_line(&t.selected_spans, line_start, line_str.len());
                let res = adjust_resolved_for_line(&resolved_display, line_start, line_str.len());
                highlight_line_with_runtime(line_str, &exec, &sel, &res, &user_words)
            } else {
                highlight_line_with_runtime(line_str, &[], &[], &[], &user_words)
            };
            line_start += line_str.len() + 1;
            let spans: Vec<Span> = tokens
                .into_iter()
                .map(|(style, text, _)| Span::styled(text, style))
                .collect();
            Line::from(spans)
        })
        .collect();

    frame.render_widget(Paragraph::new(lines), inner);
}

fn render_vu_meter(frame: &mut Frame, app: &App, area: Rect) {
    let theme = theme::get();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::new().fg(theme.ui.border));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let vu = VuMeter::new(app.metrics.peak_left, app.metrics.peak_right);
    frame.render_widget(vu, inner);
}

fn render_active_patterns(frame: &mut Frame, app: &App, snapshot: &SequencerSnapshot, area: Rect) {
    use crate::widgets::MuteStatus;

    let theme = theme::get();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::new().fg(theme.ui.border));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let patterns: Vec<(usize, usize, usize)> = snapshot
        .active_patterns
        .iter()
        .map(|p| (p.bank, p.pattern, p.iter))
        .collect();

    let mute_status: Vec<MuteStatus> = snapshot
        .active_patterns
        .iter()
        .map(|p| {
            if app.mute.is_soloed(p.bank, p.pattern) {
                MuteStatus::Soloed
            } else if app.mute.is_muted(p.bank, p.pattern) {
                MuteStatus::Muted
            } else if app.mute.is_effectively_muted(p.bank, p.pattern) {
                MuteStatus::EffectivelyMuted
            } else {
                MuteStatus::Normal
            }
        })
        .collect();

    let step_info = snapshot
        .get_step(app.editor_ctx.bank, app.editor_ctx.pattern)
        .map(|step| (step, app.current_edit_pattern().length));

    let mut widget = ActivePatterns::new(&patterns).with_mute_status(&mute_status);
    if let Some((step, total)) = step_info {
        widget = widget.with_step(step, total);
    }
    frame.render_widget(widget, inner);
}
