"""CSV upload page with auto-detection and validation preview."""

import streamlit as st

from frontend import api_client


def show_upload_page():
    project = st.session_state.get("current_project")
    if not project:
        st.warning("No project selected")
        return

    st.title(f"Upload Data: {project['name']}")

    # Back button
    if st.button("< Back to Dashboard"):
        st.session_state["page"] = "dashboard"
        st.rerun()

    st.markdown("Upload your ad platform CSV export. We'll auto-detect the format.")

    # Download templates
    st.markdown("**Need a template?**")
    cols = st.columns(4)
    platforms = ["meta_ads", "google_ads", "tiktok_ads", "generic"]
    labels = ["Meta Ads", "Google Ads", "TikTok Ads", "Generic"]
    for col, platform, label in zip(cols, platforms, labels):
        with col:
            st.markdown(f"[{label} Template](/templates/{platform})")

    # File uploader
    uploaded_file = st.file_uploader("Choose a CSV file", type=["csv"])

    if uploaded_file:
        st.info(f"File: {uploaded_file.name} ({uploaded_file.size:,} bytes)")

        if st.button("Upload & Parse"):
            with st.spinner("Uploading and parsing..."):
                resp = api_client.upload_file(
                    f"/projects/{project['id']}/upload", uploaded_file
                )

            if resp.status_code == 201:
                result = resp.json()
                st.success(
                    f"Detected platform: **{result['platform'].upper()}** | "
                    f"Rows: {result['row_count']:,} | "
                    f"Channels: {', '.join(result.get('channel_columns', {}).get('channels', []))}"
                )

                # Show preview
                preview_resp = api_client.get(f"/projects/{project['id']}/data/preview")
                if preview_resp.status_code == 200:
                    preview = preview_resp.json()
                    st.subheader("Data Preview")
                    st.dataframe(preview["preview"][:20])

                    st.subheader("Ready to Train")
                    if st.button("Go to Training"):
                        st.session_state["page"] = "training"
                        st.rerun()
            else:
                error = resp.json()
                if isinstance(error.get("detail"), dict):
                    st.error("Validation errors:")
                    for err in error["detail"].get("validation_errors", []):
                        st.warning(f"- {err}")
                else:
                    st.error(error.get("detail", "Upload failed"))
