use actix_web::{web, HttpResponse, Responder};
use serde::Deserialize;
use sqlx::PgPool;

use crate::{
    endpoints::IdPath,
    models::{Role, User},
};

#[derive(Deserialize)]
struct ToggleQuery {
    field: String,
}

#[actix_web::post("/users/{id}/toggle")]
pub async fn post(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    path: web::Path<IdPath>,
    query: web::Query<ToggleQuery>,
) -> impl Responder {
    // Todo: rewrite
    if user.id != path.id && user.role != Role::Admin && user.role != Role::AreaManager {
        return HttpResponse::Unauthorized().finish();
    }

    let user = if user.id != path.id {
        User::read_by_id(pool.get_ref(), path.id).await.unwrap().unwrap()
    } else {
        user.into_inner()
    };

    match query.field.as_str() {
        "locked" => {
            User::update(
                pool.get_ref(),
                user.id,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                Some(!user.locked),
            )
            .await
            .unwrap();

            if !user.locked {
                return HttpResponse::Ok().body(format!(
                    r##"<svg class="icon">
                          <use href="/static/feather-sprite.svg#unlock" />
                      </svg>
                      <span>Entsperren</span>
                    <div id="user-{id}-locked" hx-swap-oob="true">ja</div>
                    <button id="user-{id}-delete" hx-swap-oob="true" class="button is-danger is-light" hx-delete="/users/{id}" hx-target="closest tr" hx-swap="delete"  hx-trigger="confirmed">
                    <svg class="icon">
                      <use href="/static/feather-sprite.svg#x-circle" />
                    </svg>
                  <span>Löschen</span>
                </button>"##,
                id = user.id));
            } else {
                return HttpResponse::Ok().body(format!(
                    r##"<svg class="icon">
                          <use href="/static/feather-sprite.svg#lock" />
                        </svg>
                      <span>Sperren</span>
                    <div id="user-{id}-locked" hx-swap-oob="true">nein</div>
                    <button id="user-{id}-delete" hx-swap-oob="true" class="button is-danger is-light" disabled hx-delete="/users/{id}" hx-target="closest tr" hx-swap="delete" hx-trigger="confirmed">
                    <svg class="icon">
                      <use href="/static/feather-sprite.svg#x-circle" />
                    </svg>
                  <span>Löschen</span>
                </button>"##,
                id = user.id));
            }
        }
        "receiveNotifications" => {
            User::update(
                pool.get_ref(),
                user.id,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                Some(!user.receive_notifications),
                None,
            )
            .await
            .unwrap();
        }
        _ => return HttpResponse::BadRequest().body("Other PATCH paths are not supported!"),
    };

    HttpResponse::Ok().finish()
}
