use core::panic;

use axum::{
    response::{IntoResponse, Redirect, Response},
    routing::{get, post, Router},
    Extension, Form,
};
use chrono::Local;
use sqlx::PgPool;

use crate::{
    auth::{AuthState, UserInfo},
    database::{
        link::{Link, LinkType},
        PsqlData,
    },
};

use super::{
    templates::{AdminTemplate, HtmlTemplate},
    NewLink,
};

pub fn get_router() -> Router {
    Router::new()
        .route("/", get(get_admin))
        .route("/new_link", post(new_link))
}

pub async fn get_admin(Extension(mut current_user): Extension<AuthState>) -> Response {
    let user_info: UserInfo = current_user.get_user().await.unwrap().clone();
    if !user_info.admin {
        return Redirect::to("/").into_response();
    }
    HtmlTemplate(AdminTemplate {}).into_response()
}

pub async fn new_link(
    Extension(mut current_user): Extension<AuthState>,
    Extension(pool): Extension<PgPool>,
    Form(new_item): Form<NewLink>,
) -> Response {
    let user_info: UserInfo = current_user.get_user().await.unwrap().clone();
    if !user_info.admin {
        return Redirect::to("/").into_response();
    }

    let new_link: Link = Link {
        id: 0,
        url: new_item.url,
        title: new_item.title,
        author: new_item.author,
        link_type: match &*new_item.link_type {
            "article" => LinkType::ARTICLE,
            "blog" => LinkType::BLOG,
            _ => panic!("Not a proper link type"),
        },
        description: get_trimmed_string(new_item.description),
        date_added: Local::now().date_naive(),
    };

    let _ = new_link.insert(&pool).await;

    Redirect::to("/admin").into_response()
}

fn get_trimmed_string(input: String) -> Option<String> {
    if input.trim().is_empty() {
        None
    } else {
        Some(input.trim().to_string())
    }
}
