"""Dashboard page: project list and creation."""

import streamlit as st

from frontend import api_client

STATUS_COLORS = {
    "completed": "green",
    "running": "orange",
    "pending": "blue",
    "failed": "red",
}


def show_dashboard():
    st.title("Projects")

    # Create new project
    with st.expander("Create New Project", expanded=False):
        with st.form("new_project"):
            name = st.text_input("Project Name")
            target = st.selectbox("Target Metric", ["revenue", "conversions", "leads"])
            currency = st.selectbox("Currency", ["USD", "EUR", "GBP"])
            submitted = st.form_submit_button("Create")

            if submitted and name:
                resp = api_client.post("/projects/", json={
                    "name": name,
                    "target_metric": target,
                    "currency": currency,
                })
                if resp.status_code == 201:
                    st.success(f"Created project: {name}")
                    st.rerun()
                else:
                    st.error(resp.json().get("detail", "Failed to create project"))

    # List projects
    resp = api_client.get("/projects/")
    if resp.status_code != 200:
        st.error("Failed to load projects")
        return

    projects = resp.json()
    if not projects:
        st.info("No projects yet. Create one above to get started.")
        return

    for project in projects:
        with st.container():
            col1, col2, col3 = st.columns([3, 1, 1])

            with col1:
                st.subheader(project["name"])
                st.caption(
                    f"Target: {project['target_metric']} | "
                    f"Datasets: {project.get('dataset_count', 0)} | "
                    f"Created: {project['created_at'][:10]}"
                )

            with col2:
                status = project.get("latest_run_status")
                if status:
                    color = STATUS_COLORS.get(status, "gray")
                    st.markdown(f":{color}[{status.upper()}]")

            with col3:
                if st.button("Open", key=f"open_{project['id']}"):
                    st.session_state["current_project"] = project
                    st.session_state["page"] = "upload"
                    st.rerun()

            st.divider()
