//! Windows-style page management interface

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

use crate::manager::app::App;
use crate::manager::page_manager::{DiscoveredPage, PageManager};

/// Page management mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageManagerMode {
    /// List existing pages
    PageList,
    /// Create new page (existing functionality)
    CreateNew,
    /// Edit selected page
    EditPage,
}

/// Page manager UI state
#[derive(Debug)]
pub struct PageManagerState {
    pub mode: PageManagerMode,
    pub selected_page_index: usize,
    pub pages: Vec<DiscoveredPage>,
    pub show_create_button: bool,
    pub show_edit_options: bool,
}

impl PageManagerState {
    pub fn new(page_manager: &PageManager) -> Self {
        Self {
            mode: PageManagerMode::PageList,
            selected_page_index: 0,
            pages: page_manager.get_pages().to_vec(),
            show_create_button: true,
            show_edit_options: false,
        }
    }

    pub fn refresh_pages(&mut self, page_manager: &PageManager) {
        self.pages = page_manager.get_pages().to_vec();
        // Adjust selected index if it's out of bounds
        if self.selected_page_index >= self.pages.len() && !self.pages.is_empty() {
            self.selected_page_index = self.pages.len() - 1;
        }
    }

    pub fn next_page(&mut self) {
        if !self.pages.is_empty() {
            self.selected_page_index = (self.selected_page_index + 1) % self.pages.len();
        }
    }

    pub fn previous_page(&mut self) {
        if !self.pages.is_empty() {
            if self.selected_page_index == 0 {
                self.selected_page_index = self.pages.len() - 1;
            } else {
                self.selected_page_index = self.selected_page_index.saturating_sub(1);
            }
        }
    }

    pub fn selected_page(&self) -> Option<&DiscoveredPage> {
        self.pages.get(self.selected_page_index)
    }
}

/// Render the Windows-style page management interface
pub fn render_page_manager_interface(
    frame: &mut Frame,
    area: Rect,
    app: &App,
    state: &PageManagerState,
) {
    match state.mode {
        PageManagerMode::PageList => render_page_list_view(frame, area, app, state),
        PageManagerMode::CreateNew => {
            // Switch to normal form view for creating new pages
            // This will be handled by the existing form UI
        }
        PageManagerMode::EditPage => render_edit_page_view(frame, area, app, state),
    }
}

/// Render the main page list view (Windows Explorer style)
fn render_page_list_view(frame: &mut Frame, area: Rect, app: &App, state: &PageManagerState) {
    // Create the main layout: header, content, status bar
    let main_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header with title and create button
            Constraint::Min(0),    // Main content area
            Constraint::Length(1), // Status bar
        ])
        .split(area);

    // Render header
    render_page_manager_header(frame, main_layout[0], app, state);

    // Create content layout: sidebar (page list) + details pane
    let content_layout = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(40), // Page list sidebar
            Constraint::Percentage(60), // Details pane
        ])
        .split(main_layout[1]);

    // Render page list sidebar
    render_page_list_sidebar(frame, content_layout[0], app, state);

    // Render details pane
    render_page_details_pane(frame, content_layout[1], app, state);

    // Render status bar
    render_page_manager_status_bar(frame, main_layout[2], app, state);
}

/// Render the header with title and action buttons
fn render_page_manager_header(frame: &mut Frame, area: Rect, app: &App, state: &PageManagerState) {
    let header_layout = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Min(0),     // Title
            Constraint::Length(18), // Command Selector
            Constraint::Length(18), // Create New Page
            Constraint::Length(18), // Save Template
        ])
        .split(area);

    // Title
    let title = app
        .translations
        .get("mgr-title")
        .cloned()
        .unwrap_or_else(|| "Page Manager".to_string());

    let title_widget = Paragraph::new(vec![Line::from(vec![
        Span::styled("📄 ", Style::default().fg(Color::Blue)),
        Span::styled(
            &title,
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(format!(" ({} pages)", state.pages.len())),
    ])])
    .block(Block::default().borders(Borders::ALL))
    .alignment(Alignment::Left);

    frame.render_widget(title_widget, header_layout[0]);

    // Command Selector button
    let cmd_selector_text = app
        .translations
        .get("mgr-cmd-selector")
        .cloned()
        .unwrap_or_else(|| "Commands".to_string());

    let cmd_selector_button = Paragraph::new(format!("[ {} ]", cmd_selector_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::Magenta)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(cmd_selector_button, header_layout[1]);

    // Create New Page button
    let create_button_text = app
        .translations
        .get("mgr-create-new")
        .cloned()
        .unwrap_or_else(|| "New Page".to_string());

    let create_button = Paragraph::new(format!("[ {} ]", create_button_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::Green)
                .fg(Color::Black)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(create_button, header_layout[2]);

    // Save Template button
    let save_template_text = app
        .translations
        .get("mgr-save-template")
        .cloned()
        .unwrap_or_else(|| "Save Tmpl".to_string());

    let save_template_button = Paragraph::new(format!("[ {} ]", save_template_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::Yellow)
                .fg(Color::Black)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(save_template_button, header_layout[3]);
}

/// Render the page list sidebar
fn render_page_list_sidebar(frame: &mut Frame, area: Rect, app: &App, state: &PageManagerState) {
    let sidebar_title = app
        .translations
        .get("mgr-pages-list")
        .cloned()
        .unwrap_or_else(|| "Pages".to_string());

    if state.pages.is_empty() {
        // Show empty state
        let empty_message = app
            .translations
            .get("mgr-no-pages")
            .cloned()
            .unwrap_or_else(|| "No pages found.\nCreate your first page!".to_string());

        let empty_widget = Paragraph::new(empty_message)
            .alignment(Alignment::Center)
            .style(Style::default().fg(Color::Gray))
            .block(Block::default().borders(Borders::ALL).title(sidebar_title))
            .wrap(Wrap { trim: true });

        frame.render_widget(empty_widget, area);
        return;
    }

    // Create list items
    let list_items: Vec<ListItem> = state
        .pages
        .iter()
        .enumerate()
        .map(|(i, page)| {
            let is_selected = i == state.selected_page_index;
            let icon = "📄";

            // Show page name and route
            let name_span = if is_selected {
                Span::styled(
                    &page.name,
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                )
            } else {
                Span::styled(&page.name, Style::default().fg(Color::White))
            };

            let route_span = Span::styled(
                format!(" ({})", page.route_config.path),
                Style::default().fg(Color::Gray),
            );

            ListItem::new(Line::from(vec![
                Span::raw(format!("{} ", icon)),
                name_span,
                route_span,
            ]))
        })
        .collect();

    let list = List::new(list_items)
        .block(Block::default().borders(Borders::ALL).title(sidebar_title))
        .highlight_style(
            Style::default()
                .bg(Color::Blue)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("▶ ");

    frame.render_stateful_widget(
        list,
        area,
        &mut ratatui::widgets::ListState::default().with_selected(Some(state.selected_page_index)),
    );
}

/// Render the page details pane
fn render_page_details_pane(frame: &mut Frame, area: Rect, app: &App, state: &PageManagerState) {
    let details_title = app
        .translations
        .get("mgr-page-details")
        .cloned()
        .unwrap_or_else(|| "Page Details".to_string());

    if let Some(selected_page) = state.selected_page() {
        // Create layout for details
        let details_layout = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(8), // Page info
                Constraint::Min(0),    // Files list
                Constraint::Length(5), // Actions
            ])
            .split(area);

        // Page information
        render_page_info(frame, details_layout[0], app, selected_page);

        // Related files
        render_related_files(frame, details_layout[1], app, selected_page);

        // Action buttons
        render_page_actions(frame, details_layout[2], app, selected_page);
    } else {
        // No selection
        let no_selection = app
            .translations
            .get("mgr-select-page")
            .cloned()
            .unwrap_or_else(|| "Select a page to view details".to_string());

        let widget = Paragraph::new(no_selection)
            .alignment(Alignment::Center)
            .style(Style::default().fg(Color::Gray))
            .block(Block::default().borders(Borders::ALL).title(details_title));

        frame.render_widget(widget, area);
    }
}

/// Render page information section
fn render_page_info(frame: &mut Frame, area: Rect, _app: &App, page: &DiscoveredPage) {
    let info_lines = vec![
        Line::from(vec![
            Span::styled(
                "Name: ",
                Style::default()
                    .fg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(&page.name, Style::default().fg(Color::White)),
        ]),
        Line::from(vec![
            Span::styled(
                "Route: ",
                Style::default()
                    .fg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(&page.route_config.path, Style::default().fg(Color::Green)),
        ]),
        Line::from(vec![
            Span::styled(
                "Template: ",
                Style::default()
                    .fg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                page.route_config.template.as_deref().unwrap_or("default"),
                Style::default().fg(Color::Yellow),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                "Priority: ",
                Style::default()
                    .fg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("{:.1}", page.route_config.priority.unwrap_or(1.0)),
                Style::default().fg(Color::Magenta),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                "Languages: ",
                Style::default()
                    .fg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(page.languages.join(", "), Style::default().fg(Color::Cyan)),
        ]),
    ];

    let info_widget = Paragraph::new(info_lines)
        .block(Block::default().borders(Borders::ALL).title("Information"))
        .wrap(Wrap { trim: true });

    frame.render_widget(info_widget, area);
}

/// Render related files list
fn render_related_files(frame: &mut Frame, area: Rect, _app: &App, page: &DiscoveredPage) {
    let file_items: Vec<ListItem> = page
        .related_files
        .iter()
        .map(|file| {
            let icon = match file.file_type {
                crate::manager::page_manager::FileType::Component => "🦀",
                crate::manager::page_manager::FileType::Route => "🗺️",
                crate::manager::page_manager::FileType::Translation => "🌐",
                crate::manager::page_manager::FileType::Style => "🎨",
            };

            let status_icon = if file.exists { "✅" } else { "❌" };
            let status_color = if file.exists {
                Color::Green
            } else {
                Color::Red
            };

            let file_name = file
                .path
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("unknown");

            let language_info = if let Some(lang) = &file.language {
                format!(" ({})", lang)
            } else {
                String::new()
            };

            ListItem::new(Line::from(vec![
                Span::raw(format!("{} {} ", icon, status_icon)),
                Span::styled(file_name, Style::default().fg(status_color)),
                Span::styled(language_info, Style::default().fg(Color::Gray)),
            ]))
        })
        .collect();

    let files_list = List::new(file_items).block(
        Block::default()
            .borders(Borders::ALL)
            .title("Related Files"),
    );

    frame.render_widget(files_list, area);
}

/// Render page action buttons
fn render_page_actions(frame: &mut Frame, area: Rect, app: &App, _page: &DiscoveredPage) {
    // Split into two rows of actions
    let rows_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(50), // First row
            Constraint::Percentage(50), // Second row
        ])
        .split(area);

    // First row: Edit actions
    let first_row_layout = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(25),
            Constraint::Percentage(25),
            Constraint::Percentage(25),
            Constraint::Percentage(25),
        ])
        .split(rows_layout[0]);

    // Second row: Version control actions
    let second_row_layout = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(25),
            Constraint::Percentage(25),
            Constraint::Percentage(25),
            Constraint::Percentage(25),
        ])
        .split(rows_layout[1]);

    // First row: Edit actions

    // Edit Page button
    let edit_text = app
        .translations
        .get("mgr-edit-page")
        .cloned()
        .unwrap_or_else(|| "Edit Page".to_string());

    let edit_button = Paragraph::new(format!("[ {} ]", edit_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::Blue)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(edit_button, first_row_layout[0]);

    // Edit All Files button
    let edit_all_text = app
        .translations
        .get("mgr-edit-all")
        .cloned()
        .unwrap_or_else(|| "Edit All".to_string());

    let edit_all_button = Paragraph::new(format!("[ {} ]", edit_all_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::Yellow)
                .fg(Color::Black)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(edit_all_button, first_row_layout[1]);

    // Refresh button
    let refresh_text = app
        .translations
        .get("mgr-refresh")
        .cloned()
        .unwrap_or_else(|| "Refresh".to_string());

    let refresh_button = Paragraph::new(format!("[ {} ]", refresh_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(refresh_button, first_row_layout[2]);

    // Delete button
    let delete_text = app
        .translations
        .get("mgr-delete")
        .cloned()
        .unwrap_or_else(|| "Delete".to_string());

    let delete_button = Paragraph::new(format!("[ {} ]", delete_text))
        .alignment(Alignment::Center)
        .style(Style::default().fg(Color::Red).add_modifier(Modifier::BOLD))
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(delete_button, first_row_layout[3]);

    // Second row: Version control actions

    // Backup button
    let backup_text = app
        .translations
        .get("mgr-backup")
        .cloned()
        .unwrap_or_else(|| "Backup".to_string());

    let backup_button = Paragraph::new(format!("[ {} ]", backup_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::Cyan)
                .fg(Color::Black)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(backup_button, second_row_layout[0]);

    // Restore button
    let restore_text = app
        .translations
        .get("mgr-restore")
        .cloned()
        .unwrap_or_else(|| "Restore".to_string());

    let restore_button = Paragraph::new(format!("[ {} ]", restore_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::Magenta)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(restore_button, second_row_layout[1]);

    // History button
    let history_text = app
        .translations
        .get("mgr-history")
        .cloned()
        .unwrap_or_else(|| "History".to_string());

    let history_button = Paragraph::new(format!("[ {} ]", history_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::Gray)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(history_button, second_row_layout[2]);

    // Run Command button
    let run_cmd_text = app
        .translations
        .get("mgr-run-cmd")
        .cloned()
        .unwrap_or_else(|| "Run Cmd".to_string());

    let run_cmd_button = Paragraph::new(format!("[ {} ]", run_cmd_text))
        .alignment(Alignment::Center)
        .style(
            Style::default()
                .bg(Color::LightGreen)
                .fg(Color::Black)
                .add_modifier(Modifier::BOLD),
        )
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(run_cmd_button, second_row_layout[3]);
}

/// Render the status bar
fn render_page_manager_status_bar(
    frame: &mut Frame,
    area: Rect,
    app: &App,
    state: &PageManagerState,
) {
    let status_text = if let Some(page) = state.selected_page() {
        let selected_text = app
            .translations
            .get("mgr-status-selected")
            .cloned()
            .unwrap_or_else(|| "Selected".to_string());
        format!(
            "{}: {} | {} files | Press F1 for help",
            selected_text,
            page.name,
            page.related_files.len()
        )
    } else {
        let ready_text = app
            .translations
            .get("mgr-status-ready")
            .cloned()
            .unwrap_or_else(|| "Ready".to_string());
        format!(
            "{} | {} pages | Press F1 for help",
            ready_text,
            state.pages.len()
        )
    };

    let status_widget = Paragraph::new(status_text)
        .style(Style::default().bg(Color::Blue).fg(Color::White))
        .alignment(Alignment::Left);

    frame.render_widget(status_widget, area);
}

/// Render edit page view (when editing a specific page)
fn render_edit_page_view(frame: &mut Frame, area: Rect, _app: &App, state: &PageManagerState) {
    if let Some(page) = state.selected_page() {
        // Show editing interface for the selected page
        let edit_info = format!(
            "Editing page: {}\nRoute: {}\nFiles: {}",
            page.name,
            page.route_config.path,
            page.related_files.len()
        );

        let edit_widget = Paragraph::new(edit_info)
            .alignment(Alignment::Center)
            .style(Style::default().fg(Color::Yellow))
            .block(Block::default().borders(Borders::ALL).title("Edit Mode"))
            .wrap(Wrap { trim: true });

        frame.render_widget(edit_widget, area);
    }
}
