use ratatui::{
    layout::{Constraint, Direction, Layout},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem},
    Frame,
};

use crate::core::provider::Provider;
use crate::core::store::Store;
use crate::core::Result;

pub struct ListScreen {
    pub providers: Vec<Provider>,
    pub selected: usize,
    pub filter: String,
    pub state: std::collections::HashMap<String, Option<String>>,
    pub status: Option<String>,
}

impl ListScreen {
    pub fn load(store: &Store) -> Result<Self> {
        let store_data = store.load()?;
        let state = store.load_state()?;
        Ok(Self {
            providers: store_data.providers,
            selected: 0,
            filter: String::new(),
            state,
            status: None,
        })
    }

    pub fn filtered(&self) -> Vec<&Provider> {
        self.providers
            .iter()
            .filter(|p| {
                if self.filter.is_empty() {
                    true
                } else {
                    p.name().to_lowercase().contains(&self.filter.to_lowercase())
                }
            })
            .collect()
    }

    pub fn move_down(&mut self) {
        let count = self.filtered().len();
        if count > 0 && self.selected + 1 < count {
            self.selected += 1;
        }
    }

    pub fn move_up(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }
}

pub fn draw(frame: &mut Frame, screen: &ListScreen) {
    let area = frame.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(0),
            Constraint::Length(1),
            Constraint::Length(1),
        ])
        .split(area);

    let main = chunks[0];
    let status_bar = chunks[1];
    let footer = chunks[2];

    let filtered = screen.filtered();
    let items: Vec<ListItem> = filtered
        .iter()
        .enumerate()
        .map(|(i, p)| {
            let is_active = screen
                .state
                .get(p.target())
                .cloned()
                .flatten()
                .map(|n| n == p.name())
                .unwrap_or(false);

            let mut spans = vec![
                Span::raw(format!("[{}] ", p.target())),
                Span::styled(
                    p.name(),
                    if is_active {
                        Style::default()
                            .fg(Color::Rgb(0xE0, 0x40, 0x40))
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default()
                    },
                ),
            ];
            if is_active {
                spans.push(Span::styled(
                    " (*)",
                    Style::default().fg(Color::Rgb(0xD4, 0xA0, 0x17)),
                ));
            }

            let style = if i == screen.selected {
                Style::default().bg(Color::DarkGray)
            } else {
                Style::default()
            };

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

    let list = List::new(items).block(
        Block::default()
            .title("罗德岛工程部 · 接入管理")
            .borders(Borders::ALL),
    );
    frame.render_widget(list, main);

    // Status bar: show last action result
    let status_text = if let Some(ref msg) = screen.status {
        Line::from(Span::styled(msg.clone(), Style::default().fg(Color::Rgb(0xD4, 0xA0, 0x17))))
    } else if screen.filter.is_empty() {
        Line::from(Span::styled(
            " / 搜索  |  j/k 移动  |  Enter/s 切换  |  q 退出",
            Style::default().fg(Color::DarkGray),
        ))
    } else {
        Line::from(Span::styled(
            format!(" 搜索: {}  |  Esc 清除  |  Enter 确认", screen.filter),
            Style::default().fg(Color::Rgb(0xD4, 0xA0, 0x17)),
        ))
    };
    frame.render_widget(status_text, status_bar);

    let footer_text = Line::from(Span::styled(
        " Closure v0.1  |  可露希尔 · 罗德岛总工程师",
        Style::default().fg(Color::DarkGray),
    ));
    frame.render_widget(footer_text, footer);
}
