// src/components/admin/admin_panel.rs

use crate::config::colors::themes::Theme;
use crate::state::pages::auth::AuthState;
use crate::state::app::state::AppState;
use crate::state::pages::admin::AdminState;
use common::proto::komp_ac::table_definition::ProfileTreeResponse;
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::Style,
    text::{Line, Span, Text},
    widgets::{Block, BorderType, Borders, List, ListItem, Paragraph, Wrap},
    Frame,
};
use super::admin_panel_admin::render_admin_panel_admin;

pub fn render_admin_panel(
    f: &mut Frame,
    app_state: &AppState,
    auth_state: &AuthState,
    admin_state: &mut AdminState,
    area: Rect,
    theme: &Theme,
    profile_tree: &ProfileTreeResponse,
    selected_profile: &Option<String>,
) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.accent))
        .style(Style::default().bg(theme.bg));

    let inner_area = block.inner(area);
    f.render_widget(block, area);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(1)])
        .split(inner_area);

    // Content
    let content_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
        .split(chunks[1]);

    if auth_state.role.as_deref() != Some("admin") {
        render_admin_panel_non_admin(
            f,
            admin_state,
            &content_chunks,
            theme,
            profile_tree,
            selected_profile,
        );
    } else {
        render_admin_panel_admin(
            f,
            chunks[1],
            app_state,
            admin_state,
            theme,
        );
    }
}

/// Renders the view for non-admin users (profile list and details).
fn render_admin_panel_non_admin(
    f: &mut Frame,
    admin_state: &AdminState,
    content_chunks: &[Rect],
    theme: &Theme,
    profile_tree: &ProfileTreeResponse,
    selected_profile: &Option<String>,
) {
    // Profile list - Use data from admin_state
    let items: Vec<ListItem> = admin_state
        .profiles
        .iter()
        .map(|p| {
            ListItem::new(Line::from(vec![
                Span::styled(
                    if Some(p) == selected_profile.as_ref() { "✓ " } else { "  " },
                    Style::default().fg(theme.accent),
                ),
                Span::styled(p, Style::default().fg(theme.fg)),
            ]))
        })
        .collect();

    let list = List::new(items)
        .block(Block::default().title("Profiles"))
        .highlight_style(Style::default().bg(theme.highlight).fg(theme.bg));

    let mut profile_list_state_clone = admin_state.profile_list_state.clone();
    f.render_stateful_widget(list, content_chunks[0], &mut profile_list_state_clone);

    // Profile details - Use selection info from admin_state
    if let Some(profile) = admin_state
        .get_selected_index()
        .and_then(|i| profile_tree.profiles.get(i))
    {
        let mut text = Text::default();
        text.lines.push(Line::from(vec![
            Span::styled("Profile: ", Style::default().fg(theme.accent)),
            Span::styled(&profile.name, Style::default().fg(theme.highlight)),
        ]));

        text.lines.push(Line::from(""));
        text.lines.push(Line::from(Span::styled(
            "Tables:",
            Style::default().fg(theme.accent),
        )));

        for table in &profile.tables {
            let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)];
            if !table.depends_on.is_empty() {
                line.push(Span::styled(
                    format!(" → {}", table.depends_on.join(", ")),
                    Style::default().fg(theme.secondary),
                ));
            }
            text.lines.push(Line::from(line));
        }

        let details_widget = Paragraph::new(text)
            .block(Block::default().title("Details"))
            .wrap(Wrap { trim: true });
        f.render_widget(details_widget, content_chunks[1]);
    }
}
