import pandas as pd 
from datetime import datetime
from pprint import pprint
import streamlit as st
from userdblib import fetch_user_by_email, fetch_user_by_id, fetch_users, insert_user, update_user, delete_user, create_table, get_new_id 
import extra_streamlit_components as stx

###########################################
# 화면 함수들                             #
###########################################

def init_router():
    return stx.Router({"/": home, "/home": home, "/add": add_new_user, "/update": update_userinfo, "/delete": delete_userinfo, "/search": search_userinfo})

def selection_changed(df):
    st.write(df)

def show_header():
    st.title("사용자 관리 시스템")

def home():
    show_header()
    col1, col2, col3, col4 = st.columns(4)
    if col3.button("사용자 추가", use_container_width=True):
        router.route("/add")
    if col4.button("사용자 검색", use_container_width=True):
        router.route("/search")
    users = fetch_users()
    df = pd.DataFrame(users, columns=['id', 'name', 'email', 'age', 'created_at'])
    st.dataframe(df, use_container_width=True, hide_index=True)

    # df에서 df["id"] + df["name"] => df["id_name"] 컬럼을 추가
    df["id_name"] = df["id"].astype(str) + ":" + df["name"]    
    selected = st.selectbox("사용자 선택", df["id_name"])
    # st.write("선택된 id_name:", selected)
    st.session_state["selected"] = selected
    col1, col2 = st.columns(2)
    if col1.button("사용자 수정", use_container_width=True):
        router.route("/update")
    if col2.button("사용자 삭제",use_container_width=True):
        router.route("/delete")

def add_new_user():
    show_header()
    st.subheader("사용자 정보 입력")
    with st.form(key='user_form'):
        name = st.text_input(label="이름")
        email = st.text_input(label="이메일")
        age = st.number_input(label="나이", min_value=0, max_value=150)
        submitted = st.form_submit_button(label='저장하기', use_container_width=True)
        if submitted:
            created_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            user = {'id': get_new_id(), 'name': name, 'email': email, 'age': age, 'created_at': created_at}
            insert_user(user)
            st.success("저장되었습니다.")
    if st.button("사용자 목록", use_container_width=True):
        router.route("/home")

def update_userinfo():
    show_header()
    st.subheader("사용자 정보 수정")
    selected = st.session_state["selected"]  # "1:전상현" 
    user = fetch_user_by_id(int(selected.split(":")[0]))
    with st.form(key='user_form'):
        id = st.text_input(label="ID", value=user["id"], disabled=True)
        name = st.text_input(label="이름", value=user["name"])
        email = st.text_input(label="이메일", value=user["email"])
        age = st.number_input(label="나이", min_value=0, max_value=150, value=user["age"])
        created_at = user["created_at"]
        submitted = st.form_submit_button(label='저장하기', use_container_width=True)
        if submitted:
            user = {'id': int(id), 'name': name, 'email': email, 'age': age, 'created_at': created_at}
            update_user(user)
            st.success("저장되었습니다.")
    if st.button("사용자 목록", use_container_width=True):
        router.route("/home")


def delete_userinfo():
    show_header()
    st.subheader("사용자 정보 삭제")
    selected = st.session_state["selected"]  # "1:전상현" 
    user = fetch_user_by_id(int(selected.split(":")[0]))
    with st.form(key='user_form'):
        id = st.text_input(label="ID", value=user["id"], disabled=True)
        name = st.text_input(label="이름", value=user["name"])
        email = st.text_input(label="이메일", value=user["email"])
        age = st.number_input(label="나이", min_value=0, max_value=150, value=user["age"])
        created_at = user["created_at"]
        submitted = st.form_submit_button(label='삭제하기', use_container_width=True)
        if submitted:
            delete_user(int(id))
            st.success("삭제되었습니다.")
            router.route("/home")
    if st.button("사용자 목록", use_container_width=True):
        router.route("/home")

def search_userinfo():
    show_header()
    st.subheader("사용자 정보 검색")
    # users = fetch_users()
    # df = pd.DataFrame(users, columns=['id', 'name', 'email', 'age', 'created_at'])
    with st.form(key='user_form'):
        search_type = st.selectbox(label="검색 유형", options=["이름", "전자메일"])
        search = st.text_input(label="검색어")
        submitted = st.form_submit_button(label='검색하기', use_container_width=True)
        if submitted:
            users = fetch_users()
            df = pd.DataFrame(users, columns=['id', 'name', 'email', 'age', 'created_at'])
            if search_type == "이름":
                df = df[df["name"].str.contains(search, case=False)]
                st.dataframe(df, use_container_width=True, hide_index=True) 
            elif search_type == "전자메일":
                df = df[df["email"].str.contains(search, case=False)]
                st.dataframe(df, use_container_width=True, hide_index=True)

            # df에서 df["id"] + df["name"] => df["id_name"] 컬럼을 추가
            df["id_name"] = df["id"].astype(str) + ":" + df["name"]    
            selected = st.selectbox("사용자 선택", df["id_name"])
            # st.write("선택된 id_name:", selected)
            st.session_state["selected"] = selected
    col1, col2 = st.columns(2)
    if col1.button("사용자 수정", use_container_width=True):
        router.route("/update")
    if col2.button("사용자 삭제",use_container_width=True):
        router.route("/delete")

    if st.button("사용자 목록", use_container_width=True):
        router.route("/home")

# main 함수
create_table()
if "selected" not in st.session_state:
    st.session_state["selected"] = None

router = init_router()
router.show_route_view()

