use crate::component::{Component, EventCx, LayoutCx, MeasureCx};
use crate::event::Event;
use crate::geom::{Pos, Rect, Size};
use crate::layout::Constraint;
use crate::node::Node;
use crate::render::RenderCx;
use crate::style::{Color, Style};

/// A scrollable container — content can be larger than the viewport.
///
/// Supports vertical and horizontal scrolling via keyboard (Up/Down/Left/Right)
/// and mouse wheel. Renders a scrollbar indicator when content overflows.
pub struct Scroll {
    child: Option<Node>,
    scroll_y: u16,
    scroll_x: u16,
    content_height: u16,
    content_width: u16,
    rect: Rect,
}

impl Scroll {
    pub fn new(child: impl Component + 'static) -> Self {
        Self {
            child: Some(Node::new(child)),
            scroll_y: 0,
            scroll_x: 0,
            content_height: 0,
            content_width: 0,
            rect: Rect::default(),
        }
    }
}

impl Component for Scroll {
    fn render(&self, cx: &mut RenderCx) {
        if let Some(child) = &self.child {
            let viewport = cx.rect;

            // Clamp scroll to valid range
            let max_scroll_y = self.content_height.saturating_sub(viewport.height);
            let max_scroll_x = self.content_width.saturating_sub(viewport.width);
            let sy = self.scroll_y.min(max_scroll_y);
            let sx = self.scroll_x.min(max_scroll_x);

            // Offset all descendant rects (wrapping to avoid saturation asymmetry)
            fn offset_all(node: &Node, dx: i16, dy: i16) {
                let mut r = node.rect();
                if dx >= 0 { r.x = r.x.wrapping_add(dx as u16); }
                else { r.x = r.x.wrapping_sub((-dx) as u16); }
                if dy >= 0 { r.y = r.y.wrapping_add(dy as u16); }
                else { r.y = r.y.wrapping_sub((-dy) as u16); }
                node.set_rect(r);
                node.component.for_each_child(&mut |c: &Node| offset_all(c, dx, dy));
            }

            offset_all(child, -(sx as i16), -(sy as i16));
            child.render_with_clip(cx.buffer, cx.focused_id, Some(viewport));
            offset_all(child, sx as i16, sy as i16);

            // Scrollbar indicator
            self.render_scrollbar(cx, viewport, sy, max_scroll_y, sx, max_scroll_x);
        }
    }

    fn measure(&self, constraint: Constraint, _cx: &mut MeasureCx) -> Size {
        Size { width: constraint.max.width, height: constraint.max.height }
    }

    fn focusable(&self) -> bool { false }

    fn event(&mut self, event: &Event, cx: &mut EventCx) {
        if matches!(event, Event::Focus | Event::Blur) { return; }

        if let Event::Key(key_event) = event {
            let old_y = self.scroll_y;
            let old_x = self.scroll_x;
            match &key_event.key {
                crate::event::Key::Up => { self.scroll_y = self.scroll_y.saturating_sub(1); }
                crate::event::Key::Down => { self.scroll_y = self.scroll_y.saturating_add(1); }
                crate::event::Key::Left => { self.scroll_x = self.scroll_x.saturating_sub(1); }
                crate::event::Key::Right => { self.scroll_x = self.scroll_x.saturating_add(1); }
                crate::event::Key::PageUp => {
                    let page = self.rect.height.max(1).saturating_sub(1);
                    self.scroll_y = self.scroll_y.saturating_sub(page);
                }
                crate::event::Key::PageDown => {
                    let page = self.rect.height.max(1).saturating_sub(1);
                    self.scroll_y = self.scroll_y.saturating_add(page);
                }
                _ => {}
            }
            if self.scroll_y != old_y || self.scroll_x != old_x {
                cx.invalidate_paint();
                return;
            }
        }

        if let Event::Mouse(mouse_event) = event {
            match mouse_event.kind {
                crate::event::MouseKind::ScrollUp => {
                    self.scroll_y = self.scroll_y.saturating_sub(1);
                    cx.invalidate_paint();
                    return;
                }
                crate::event::MouseKind::ScrollDown => {
                    self.scroll_y = self.scroll_y.saturating_add(1);
                    cx.invalidate_paint();
                    return;
                }
                _ => {}
            }
        }

        // Forward events to child in capture phase
        if cx.phase() == crate::event::EventPhase::Capture {
            if let Some(child) = &mut self.child {
                let mut child_cx = EventCx::with_task_sender(
                    &mut child.dirty, cx.global_dirty, cx.quit,
                    cx.phase, cx.propagation_stopped, cx.task_sender.clone(),
                );
                child.component.event(event, &mut child_cx);
            }
        }
    }

    fn layout(&mut self, rect: Rect, _cx: &mut LayoutCx) {
        self.rect = rect;
        if let Some(child) = &mut self.child {
            let child_size = child.measure(Constraint::loose(65535, 65535));
            self.content_height = child_size.height;
            self.content_width = child_size.width;
            let child_rect = Rect {
                x: rect.x, y: rect.y,
                width: child_size.width.max(rect.width),
                height: child_size.height.max(rect.height),
            };
            child.layout(child_rect);
        }
    }

    fn for_each_child(&self, f: &mut dyn FnMut(&Node)) {
        if let Some(child) = &self.child { f(child); }
    }
    fn for_each_child_mut(&mut self, f: &mut dyn FnMut(&mut Node)) {
        if let Some(child) = &mut self.child { f(child); }
    }
    fn style(&self) -> Style { Style::default() }
}

impl Scroll {
    /// Draws scrollbar indicators on the right and bottom edges.
    fn render_scrollbar(&self, cx: &mut RenderCx, vp: Rect, sy: u16, max_y: u16, sx: u16, max_x: u16) {
        let bar_style = Style::default().bg(Color::Gray);

        // Vertical scrollbar (right edge)
        if max_y > 0 {
            let thumb_h = ((vp.height as u64 * vp.height as u64) / (vp.height as u64 + max_y as u64)) as u16;
            let thumb_h = thumb_h.max(1);
            let thumb_y = if max_y > 0 {
                vp.y.saturating_add((sy as u64 * (vp.height.saturating_sub(thumb_h)) as u64 / max_y as u64) as u16)
            } else {
                vp.y
            };

            for y in vp.y..vp.y.saturating_add(vp.height) {
                let x = vp.x.saturating_add(vp.width.saturating_sub(1));
                if y >= thumb_y && y < thumb_y.saturating_add(thumb_h) {
                    cx.buffer.write_text(Pos { x, y }, vp, "█", &bar_style);
                } else if let Some(cell) = cx.buffer.get_mut(x, y) {
                    cell.style.bg = Some(Color::Black);
                }
            }
        }

        // Horizontal scrollbar (bottom edge)
        if max_x > 0 {
            let thumb_w = ((vp.width as u64 * vp.width as u64) / (vp.width as u64 + max_x as u64)) as u16;
            let thumb_w = thumb_w.max(1);
            let thumb_x = if max_x > 0 {
                vp.x.saturating_add((sx as u64 * (vp.width.saturating_sub(thumb_w)) as u64 / max_x as u64) as u16)
            } else {
                vp.x
            };

            for x in vp.x..vp.x.saturating_add(vp.width) {
                let y = vp.y.saturating_add(vp.height.saturating_sub(1));
                if x >= thumb_x && x < thumb_x.saturating_add(thumb_w) {
                    cx.buffer.write_text(Pos { x, y }, vp, "█", &bar_style);
                } else if let Some(cell) = cx.buffer.get_mut(x, y) {
                    cell.style.bg = Some(Color::Black);
                }
            }
        }
    }
}
