// src/pages/forms/ui.rs
use crate::config::colors::themes::Theme;
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
    style::Style,
    widgets::{Block, Borders, Paragraph},
    Frame,
};
use canvas::{
    render_canvas, render_suggestions_dropdown, DefaultCanvasTheme, FormEditor,
};
use crate::pages::forms::FormState;

pub fn render_form_page(
    f: &mut Frame,
    area: Rect,
    editor: &FormEditor<FormState>,
    table_name: &str,
    theme: &Theme,
    total_count: u64,
    current_position: u64,
) {
    let card_title = format!(" {} ", table_name);

    let adresar_card = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme.border))
        .title(card_title)
        .style(Style::default().bg(theme.bg).fg(theme.fg));

    f.render_widget(adresar_card, area);

    let inner_area = area.inner(Margin {
        horizontal: 1,
        vertical: 1,
    });

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

    let count_position_text = if total_count == 0 && current_position == 1 {
        "Total: 0 | New Entry".to_string()
    } else if current_position > total_count && total_count > 0 {
        format!("Total: {} | New Entry ({})", total_count, current_position)
    } else if total_count == 0 && current_position > 1 {
        format!("Total: 0 | New Entry ({})", current_position)
    } else {
        format!(
            "Total: {} | Position: {}/{}",
            total_count, current_position, total_count
        )
    };

    let count_para = Paragraph::new(count_position_text)
        .style(Style::default().fg(theme.fg))
        .alignment(Alignment::Left);
    f.render_widget(count_para, main_layout[0]);

    // --- FORM RENDERING (Using persistent FormEditor) ---
    let active_field_rect = render_canvas(f, main_layout[1], editor, theme);
    if let Some(active_rect) = active_field_rect {
        render_suggestions_dropdown(
            f,
            main_layout[1],
            active_rect,
            &DefaultCanvasTheme,
            editor,
        );
    }
}
