import streamlit as st
import os
import pandas as pd
from pathlib import Path
import time
from datetime import datetime

def show_training_data_manager(cfg):
    st.subheader("📂 Gestione Campioni Training")
    
    try:
        raw_path = cfg.get('collect_train', {}).get('samples_dir', '/data/train/samples')
        samples_dir = Path(raw_path)
    except Exception as e:
        st.error(f"Errore config: {e}")
        return

    # --- 1. RECUPERO E FILTRO DATI ---
    all_files = [f for f in os.listdir(samples_dir) if f.endswith('.csv')]
    files_data = []
    
    for file in all_files:
        path = samples_dir / file
        ts = os.path.getmtime(path)
        files_data.append({
            "File": file,
            "Data": datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M"),
            "ts": ts
        })

    df = pd.DataFrame(files_data).sort_values("ts", ascending=False)

    # Barra di ricerca
    search = st.text_input("🔍 Cerca coordinata:", "").strip().lower()
    if search:
        df = df[df['File'].str.lower().str.contains(search)]

    # --- 2. VISUALIZZAZIONE COMPATTA (SENZA TREMOLIO) ---
    # Usiamo le colonne per restringere la tabella al centro
    col_tab, col_empty = st.columns([3, 1]) 
    
    with col_tab:
        # st.table non ha scrollbar e non ha interazioni JS che causano tremolio
        st.table(df[["File", "Data"]].head(20)) 

    st.divider()

    # --- 3. AZIONI ---
    st.markdown("### 🛠️ Azioni")
    selected = st.selectbox("Seleziona file per operare:", df["File"].tolist())
    
    if selected:
        file_path = samples_dir / selected
        c1, c2, c3 = st.columns([1,1,1])
        
        with c1:
            if st.button("👁️ Dettagli", use_container_width=True):
                content = pd.read_csv(file_path, sep=";")
                st.markdown(f"**Dati di `{selected}`**")
                st.table(content.T.reset_index().rename(columns={'index': 'AP', 0: 'RSSI'}))
        
        with c2:
            with open(file_path, "rb") as f:
                st.download_button("📥 Scarica", f, file_name=selected, use_container_width=True)
        
        with c3:
            if st.button("🗑️ Elimina", use_container_width=True, type="primary"):
                os.remove(file_path)
                st.rerun()

    # Stats discrete in sidebar
    st.sidebar.caption(f"Totale campioni: {len(all_files)}")
