use adw::prelude::*;
use chrono::Datelike;

/// Create a date picker ActionRow with a calendar popover.
/// Returns (ActionRow, Label) where the label holds the selected date string (YYYY-MM-DD).
pub fn make_date_row(title: &str, initial_date: &str) -> (adw::ActionRow, gtk::Label) {
    let date_label = gtk::Label::new(Some(initial_date));
    date_label.set_halign(gtk::Align::End);
    date_label.set_hexpand(true);

    let calendar = gtk::Calendar::new();
    let popover = gtk::Popover::new();
    popover.set_child(Some(&calendar));

    let date_menu_btn = gtk::MenuButton::new();
    date_menu_btn.set_popover(Some(&popover));
    let calendar_icon = gtk::Image::from_icon_name("outlay-calendar");
    calendar_icon.set_pixel_size(28);
    date_menu_btn.set_child(Some(&calendar_icon));
    date_menu_btn.add_css_class("flat");
    date_menu_btn.set_tooltip_text(Some("Pick date"));

    let date_box = gtk::Box::new(gtk::Orientation::Horizontal, 8);
    date_box.append(&date_label);
    date_box.append(&date_menu_btn);

    let row = adw::ActionRow::builder()
        .title(title)
        .build();
    row.add_suffix(&date_box);
    row.set_activatable_widget(Some(&date_menu_btn));

    let date_label_ref = date_label.clone();
    let popover_ref = popover.clone();
    calendar.connect_day_selected(move |cal| {
        let dt = cal.date();
        let formatted = dt.format("%Y-%m-%d").unwrap().to_string();
        date_label_ref.set_label(&formatted);
        popover_ref.popdown();
    });

    // Select the initial date on the calendar if provided
    if let Ok(date) = chrono::NaiveDate::parse_from_str(initial_date, "%Y-%m-%d") {
        let glib_dt = gtk::glib::DateTime::from_local(
            date.year(),
            date.month() as i32,
            date.day() as i32,
            0, 0, 0.0,
        );
        if let Ok(dt) = glib_dt {
            calendar.select_day(&dt);
        }
    }

    (row, date_label)
}
