// ui/dialogo_url.rs — Diálogo para agregar un URL de streaming al pautaje
//
// Formato guardado en el .com para streaming con duración:
//   URL\tDURACION_SEGS|dias|inicio|fin
// Si duración = 0 se guarda solo la URL sin el tab.

use gtk4 as gtk;
use gtk::prelude::*;
use gtk::{
    ApplicationWindow, Box as GtkBox, Button, Entry, Label,
    ListBox, ListBoxRow, ListStore, Orientation, ScrolledWindow, SpinButton, Window,
};
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;

use crate::i18n::tr;
use crate::models::{EntradaPautaje, Estado};
use crate::storage;
use crate::ui::comun::recargar_store;

fn history_path() -> PathBuf {
    dirs::home_dir().unwrap().join(".gradio/data/url_history")
}

fn load_history() -> Vec<String> {
    std::fs::read_to_string(history_path())
        .unwrap_or_default()
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.to_string())
        .collect()
}

fn save_to_history(url: &str) {
    let path = history_path();
    let mut history = load_history();
    history.retain(|u| u != url);
    history.insert(0, url.to_string());
    history.truncate(20);
    let content = history.join("\n") + "\n";
    let _ = std::fs::write(path, content);
}

fn delete_from_history(url: &str) {
    let path = history_path();
    let mut history = load_history();
    history.retain(|u| u != url);
    let content = if history.is_empty() {
        String::new()
    } else {
        history.join("\n") + "\n"
    };
    let _ = std::fs::write(path, content);
}

pub fn mostrar_dialogo_url(
    padre: &ApplicationWindow,
    estado: Rc<RefCell<Estado>>,
    store_pautaje: ListStore,
) {
    let win = Window::builder()
        .title(tr("dialogo.url.title"))
        .transient_for(padre)
        .modal(true)
        .default_width(480)
        .resizable(true)
        .default_height(360)
        .build();

    let vbox = GtkBox::new(Orientation::Vertical, 8);
    vbox.set_margin_top(16);
    vbox.set_margin_bottom(16);
    vbox.set_margin_start(16);
    vbox.set_margin_end(16);

    // ── URL ──────────────────────────────────────────────────────────────
    vbox.append(&Label::new(Some(tr("dialogo.url.label"))));
    let entry_url = Entry::new();
    entry_url.set_hexpand(true);
    entry_url.set_placeholder_text(Some("http://stream.ejemplo.com:8000/radio"));
    vbox.append(&entry_url);

    // ── Historial ────────────────────────────────────────────────────────
    let history_entries = load_history();
    if !history_entries.is_empty() {
        let lbl_hist = Label::new(Some(tr("dialogo.url.history")));
        lbl_hist.set_halign(gtk4::Align::Start);
        vbox.append(&lbl_hist);

        let hist_list = ListBox::new();
        hist_list.set_selection_mode(gtk4::SelectionMode::None);

        for url in &history_entries {
            let row = ListBoxRow::new();
            row.set_selectable(false);
            let hbox = GtkBox::new(Orientation::Horizontal, 6);
            hbox.set_margin_top(2);
            hbox.set_margin_bottom(2);
            hbox.set_margin_start(4);
            hbox.set_margin_end(4);

            let lbl = Label::new(Some(url.as_str()));
            lbl.set_hexpand(true);
            lbl.set_halign(gtk4::Align::Start);
            lbl.set_max_width_chars(48);
            lbl.set_ellipsize(gtk4::pango::EllipsizeMode::End);

            let btn_use = Button::with_label(tr("dialogo.url.use"));
            let btn_del = Button::with_label("✕");
            btn_del.set_tooltip_text(Some(tr("dialogo.url.delete_tip")));

            hbox.append(&lbl);
            hbox.append(&btn_use);
            hbox.append(&btn_del);
            row.set_child(Some(&hbox));
            hist_list.append(&row);

            // "Usar" → copia el URL al campo de texto
            {
                let entry_c = entry_url.clone();
                let url_c = url.clone();
                btn_use.connect_clicked(move |_| {
                    entry_c.set_text(&url_c);
                });
            }
            // "✕" → elimina del historial y oculta la fila
            {
                let url_c = url.clone();
                let row_c = row.clone();
                btn_del.connect_clicked(move |_| {
                    delete_from_history(&url_c);
                    row_c.set_visible(false);
                });
            }
        }

        let hist_scroll = ScrolledWindow::new();
        hist_scroll.set_vexpand(false);
        hist_scroll.set_min_content_height(80);
        hist_scroll.set_max_content_height(150);
        hist_scroll.set_child(Some(&hist_list));
        vbox.append(&hist_scroll);
    }

    // ── Duración ──────────────────────────────────────────────────────────
    let hbox_dur = GtkBox::new(Orientation::Horizontal, 8);
    hbox_dur.append(&Label::new(Some(tr("dialogo.url.duration"))));

    // SpinButton: 0 = sin límite, 1..86400 (24h)
    let adj = gtk::Adjustment::new(
        30.0,    // valor inicial
        0.0,     // mínimo (0 = sin límite / continuo)
        86400.0, // máximo (24 horas)
        1.0,     // paso
        60.0,    // paso de página
        0.0,     // tamaño de página (no usado)
    );
    let spin_dur = SpinButton::new(Some(&adj), 1.0, 0);
    spin_dur.set_width_chars(8);
    spin_dur.set_tooltip_text(Some(tr("dialogo.url.duration_tip")));
    hbox_dur.append(&spin_dur);

    let lbl_hint = Label::new(Some(tr("dialogo.url.continuous_hint")));
    lbl_hint.add_css_class("dim-label");
    hbox_dur.append(&lbl_hint);
    vbox.append(&hbox_dur);

    // ── Botones ───────────────────────────────────────────────────────────
    let hbox_btns = GtkBox::new(Orientation::Horizontal, 6);
    hbox_btns.set_halign(gtk::Align::End);
    let btn_cancelar = Button::with_label(tr("btn.cancel"));
    let btn_aceptar  = Button::with_label(tr("dialogo.url.add"));
    btn_aceptar.add_css_class("suggested-action");
    hbox_btns.append(&btn_cancelar);
    hbox_btns.append(&btn_aceptar);
    vbox.append(&hbox_btns);

    win.set_child(Some(&vbox));

    {
        let wc = win.clone();
        btn_cancelar.connect_clicked(move |_| wc.close());
    }
    {
        let wc = win.clone();
        let eu = entry_url.clone();
        let sd = spin_dur.clone();
        btn_aceptar.connect_clicked(move |_| {
            let url = eu.text().to_string();
            if !url.trim().is_empty() {
                let duracion = sd.value() as u32;
                // Formato de ruta: URL  o  URL\tSEGS si duracion > 0
                let ruta = if duracion > 0 {
                    format!("{}\t{}", url.trim(), duracion)
                } else {
                    url.trim().to_string()
                };
                let e = estado.borrow();
                let entrada = EntradaPautaje {
                    ruta,
                    dias: e.dias.clone(),
                    inicio: e.fecha_inicio,
                    fin: e.fecha_fin,
                };
                storage::agregar_entrada(&e.tipo, e.hora, e.minuto, entrada);
                recargar_store(&store_pautaje, &e.tipo, e.hora, e.minuto);
                // Guardar en historial
                save_to_history(url.trim());
            }
            wc.close();
        });
    }

    win.present();
}
