use askama_axum::Template;
use axum::{extract::{Path, State}, response::IntoResponse, Extension};
use http::Request;
use sqlx::SqlitePool;

use crate::{HtmlTemplate, UserData};

#[derive(Template)]
#[template(path = "profile.html")]
struct ProfileTemplate {
    logged_in: bool,
    name: String,
    user: UserData
}

/// Handles the profile page.
pub async fn profile<T>(
    Extension(user_data): Extension<Option<UserData>>,
    _request: Request<T>,
) -> impl IntoResponse {
    // Extract the user's name from the user data.
    let user_name = user_data.as_ref().map(|s| s.name.clone());
    let logged_in = user_data.is_some();
    let name = user_name.unwrap_or_default();
  
    // Extract the user data.
    let user = user_data.as_ref().unwrap();

    // Create the profile template.
    let template = ProfileTemplate { logged_in, name, user: user.clone() };
    return HtmlTemplate(template)
}

 pub async fn user_profile<T>(
    Path(user_id): Path<i64>,
    State(db_pool): State<SqlitePool>,
    Extension(user_data): Extension<Option<UserData>>,
    _request: Request<T>,
) -> impl IntoResponse {
    // Extract the user's name from the user data.
    let user_name = user_data.as_ref().map(|s| s.name.clone());
    let logged_in = user_data.is_some();
    let name = user_name.unwrap_or_default();
  
    // Extract the user data.
    let user = sqlx::query_as!(
        UserData,
        "SELECT * FROM users WHERE id = ?",
        user_id
    )
    .fetch_one(&db_pool)
    .await
    .unwrap();

    // Create the profile template.
    let template = ProfileTemplate { logged_in, name, user: user };
    return HtmlTemplate(template)
}

#[derive(Template)]
#[template(path = "useradmin.html")]
struct UserAdminTemplate {
    logged_in: bool,
    name: String,
    users: Vec<UserData>
}

pub async fn useradmin<T>(
    Extension(user_data): Extension<Option<UserData>>,
    State(db_pool): State<SqlitePool>,
    _request: Request<T>,
) -> impl IntoResponse {

    let user_email = user_data.map(|s| s.email);
    let logged_in = user_email.is_some();
    let name = user_email.unwrap_or_default();

    let users = sqlx::query_as::<_, UserData>("SELECT * FROM users")
    .fetch_all(&db_pool)
    .await
    .unwrap();

    let template = UserAdminTemplate { logged_in, name, users };
    HtmlTemplate(template)
}
