use crate::components::Component;
use crate::services::GitService;
use crate::app::{AppState, Action, reducer};
use crate::errors::ComponentError;
use crate::input::InputEvent;
use crate::ui::style;
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::widgets::{List, ListItem};
use ratatui::style::Style;
use crossterm::event::{KeyCode, KeyEventKind};
use std::sync::Arc;

pub struct TagsPane {
    git_service: Arc<GitService>,
}

impl TagsPane {
    pub fn new(git_service: Arc<GitService>) -> Self {
        Self { git_service }
    }
}

impl Component for TagsPane {
    fn handle_event(
        &mut self,
        event: InputEvent,
        state: &AppState,
    ) -> Result<Option<Action>, ComponentError> {
        match event {
            InputEvent::Key(key) if key.kind == KeyEventKind::Press => {
                match key.code {
                    KeyCode::Esc => {
                        Ok(Some(Action::FocusPrev)) // Go back to Status pane
                    }
                    KeyCode::Char('k') | KeyCode::Up => {
                        Ok(Some(Action::TagUp))
                    }
                    KeyCode::Char('j') | KeyCode::Down => {
                        Ok(Some(Action::TagDown))
                    }
                    KeyCode::Enter => {
                        // Checkout tag
                        if let Some(tag) = state.tags.get(state.tag_selected) {
                            Ok(Some(Action::CheckoutTag(tag.name.clone())))
                        } else {
                            Ok(None)
                        }
                    }
                    KeyCode::Char('D') => {
                        // Delete tag
                        if let Some(tag) = state.tags.get(state.tag_selected) {
                            Ok(Some(Action::DeleteTag(tag.name.clone())))
                        } else {
                            Ok(None)
                        }
                    }
                    _ => Ok(None),
                }
            }
            _ => Ok(None),
        }
    }
    
    fn update(
        &mut self,
        action: Action,
        state: &mut AppState,
    ) -> Result<(), ComponentError> {
        match action {
            Action::RefreshTags => {
                // Refresh tags from git
                let path = state.repo_path.clone();
                match self.git_service.tags(&path) {
                    Ok(tags) => {
                        *state = reducer(state.clone(), Action::SetTags(tags));
                    }
                    Err(e) => {
                        tracing::warn!(error = %e, "tags error");
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }
    
    fn render(&mut self, frame: &mut Frame, area: Rect, state: &AppState) {
        let theme = &state.theme;
        let selection_style = style::selection(theme);

        let items: Vec<ListItem> = state.tags
            .iter()
            .enumerate()
            .map(|(i, tag)| {
                let style = if i == state.tag_selected {
                    selection_style
                } else {
                    Style::default().fg(theme.untracked_color())
                };
                
                ListItem::new(format!("{} - {}", tag.name, tag.message))
                    .style(style)
            })
            .collect();
        
        let list = List::new(items)
            .style(style::body_style(theme))
            .block(style::pane_block(theme, "Tags", false));
        
        frame.render_widget(list, area);
    }
    
    fn name(&self) -> &'static str {
        "TagsPane"
    }
}
