use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use ratatui::Frame;

use crate::tui::app::PendingAction;
use crate::tui::theme;

pub fn render(f: &mut Frame, area: Rect, action: &PendingAction) {
    let popup = centered_rect(35, 30, area);
    f.render_widget(Clear, popup);

    let block = Block::default()
        .title(" Confirm ")
        .title_style(theme::title())
        .borders(Borders::ALL)
        .border_style(ratatui::style::Style::default().fg(theme::BORDER_FOCUS))
        .style(ratatui::style::Style::default().bg(theme::SURFACE));

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

    let message = match action {
        PendingAction::CancelOrder { symbol, order_id } => {
            let short_id = if order_id.len() > 8 {
                &order_id[..8]
            } else {
                order_id
            };
            format!("Cancel order {short_id}.. on\n{symbol}?")
        }
        PendingAction::ClosePosition {
            symbol,
            side,
            quantity,
        } => {
            format!("Close {side} {quantity} on\n{symbol}?")
        }
        PendingAction::PlaceOrder {
            symbol,
            side,
            quantity,
            price,
        } => {
            let price_info = price
                .as_ref()
                .map(|p| format!(" @ {p}"))
                .unwrap_or_else(|| " (market)".to_string());
            format!("{side} {quantity} {symbol}{price_info}?")
        }
        PendingAction::NukeOrders { symbol, count } => {
            format!("Cancel ALL {count} orders on\n{symbol}?")
        }
        PendingAction::NukePositions { positions } => {
            let mut msg = format!("Close ALL {} positions?\n", positions.len());
            for (sym, side, qty) in positions.iter().take(5) {
                msg.push_str(&format!("  {side} {qty} {sym}\n"));
            }
            if positions.len() > 5 {
                msg.push_str(&format!("  ...and {} more", positions.len() - 5));
            }
            msg
        }
        PendingAction::NukeAll {
            order_count,
            positions,
        } => {
            let pos_count = positions.len();
            let mut msg =
                format!("NUKE: Cancel {order_count} orders\nAND close {pos_count} positions?");
            for (sym, side, qty) in positions.iter().take(3) {
                msg.push_str(&format!("\n  {side} {qty} {sym}"));
            }
            if positions.len() > 3 {
                msg.push_str(&format!("\n  ...and {} more", positions.len() - 3));
            }
            msg
        }
    };

    let mut lines = vec![Line::from("")];
    for msg_line in message.lines() {
        lines.push(Line::from(Span::styled(
            format!("  {msg_line}"),
            theme::normal(),
        )));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  y", theme::highlight()),
        Span::styled("/Enter confirm  ", theme::dim()),
    ]));
    lines.push(Line::from(vec![
        Span::styled("  n", theme::highlight()),
        Span::styled("/Esc cancel", theme::dim()),
    ]));

    let paragraph = Paragraph::new(lines);
    f.render_widget(paragraph, inner);
}

fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}
