use crate::{
    language::language,
    page::{MyMessage, Page},
    AppState, NameUpdateError,
};
use axum::{
    extract::{Path, State},
    http::HeaderMap,
    response::{IntoResponse, Response},
    routing::{get, post},
    Form, Router,
};
use axum_extra::extract::{CookieJar, PrivateCookieJar};
use maud::{html, Markup, PreEscaped};
use serde::Deserialize;
use uuid::Uuid;

async fn index(
    State(state): State<AppState>,
    cookies: PrivateCookieJar,
    lang_cookies: CookieJar,
    headers: HeaderMap,
) -> Response {
    retu(state, cookies, lang_cookies, headers, None).await
}

async fn retu(
    state: AppState,
    cookies: PrivateCookieJar,
    lang_cookies: CookieJar,
    headers: HeaderMap,
    message: Option<MyMessage>,
) -> Response {
    let backend = &state.backend;
    let (cookies, req) = backend.client_full(cookies, &lang_cookies, &headers).await;

    // Check if user is admin
    let is_admin = cookies.get("admin_session").is_some();
    let client = req.client;
    rust_i18n::set_locale(&req.lang.to_string());

    let sightings = backend.sightings_for_client(&client).await;
    let amount_total_cameras = backend.amount_total_cameras().await;
    let highscore = backend.highscore(&client).await;
    let amount_participants = backend.amount_participants().await;

    let mut page = Page::new(req.lang);
    if let Some(message) = message {
        page.set_message(message);
    }
    let markup = page.content(html! {
        hgroup {
            h1 { (t!("game_title")) }
        }
        p {
            (t!("game_explanation_todo"))
        }

        div.mb-sm { (t!("ask_to_change_name", name = client.get_display_name())) }

        form action="/game" method="post" {
            fieldset role="group" {
                input
                    name="name"
                    placeholder=(t!("funny_name_change_placeholder"))
                    aria-label="Name"
                    required;
                input type="submit" value=(t!("save_button"));
            }
        }

        p.mb-0 {
            ({
                t!(
                    "cameras_found", found = sightings.len(), total =
                    amount_total_cameras
                )
            })
            progress value=(sightings.len()) max=(amount_total_cameras);
        }

        ol.flex.small {
            @for sighting in &sightings {
                li { (sighting.camera.name) }
            }
        }

        p {
            h2 { (t!("highscore_title")) }
            ul.iterated {
                @for rank in highscore {
                    @if rank.show_dots_above {
                        li.no-border {
                            span {
                                "⋮"
                            }
                        }
                    }
                    li.card {
                        span {
                            span.font-headline.rank.text-muted { (rank.rank) "." }
                            @if rank.client == client { (PreEscaped("<mark id='ranking'>")) }
                            (rank.client.get_display_name())
                            @if rank.client == client { (PreEscaped("</mark>")) }
                            @if is_admin && rank.client.name.is_some() && rank.client.name.as_ref().unwrap() != "***" {
                                form method="POST" action="/game/ban-name" style="display: inline; margin-left: 0.5rem;" {
                                    input type="hidden" name="name" value=(rank.client.name.as_ref().unwrap());
                                    input type="submit" value="Block" class="secondary" style="font-size: 0.8rem; padding: 0.25rem 0.5rem;";
                                }
                            }
                        }
                        span.font-headline.font-lg {
                            (rank.amount)
                            (PreEscaped("&nbsp;"))
                            (t!("icon_camera"))
                        }
                    }
                }
            }
            span.small {
                (t!("amount_participants", amount = amount_participants))
            }
        }
    });

    (cookies, markup).into_response()
}

async fn game(
    State(state): State<AppState>,
    cookies: PrivateCookieJar,
    lang_cookies: CookieJar,
    headers: HeaderMap,
    Path(uuid): Path<String>,
) -> Response {
    let backend = &state.backend;
    let (cookies, req) = backend.client_full(cookies, &lang_cookies, &headers).await;
    let client = req.client;
    rust_i18n::set_locale(req.lang.to_locale());

    let Ok(uuid) = Uuid::parse_str(&uuid) else {
        return not_found(lang_cookies, headers).await.into_response();
    };

    let Some(camera) = backend.get_camera(&uuid).await else {
        // Check if user is admin
        if cookies.get("admin_session").is_some() {
            // Redirect to camera add form with pre-filled UUID
            return axum::response::Redirect::to(&format!("/admin/cameras/add?uuid={}", uuid))
                .into_response();
        }
        return not_found(lang_cookies, headers).await.into_response();
    };

    let message = if let Ok(number) = backend.client_found_camera(&client, &camera).await {
        MyMessage::FoundCam(camera.name, number)
    } else {
        MyMessage::Error(
            t!("error_already_found_title").into(),
            t!("error_already_found_body").into(),
            t!("error_already_found_footer").into(),
        )
    };

    retu(state, cookies, lang_cookies, headers, Some(message)).await
}

async fn not_found(cookies: CookieJar, headers: HeaderMap) -> Markup {
    let lang = language(&cookies, &headers);
    Page::new(lang).content(html! {
        h1 { (t!("not_found_title")) }
    })
}

#[derive(Deserialize)]
struct NameForm {
    name: String,
}

#[derive(Deserialize)]
struct BanNameForm {
    name: String,
}

async fn set_name(
    State(state): State<AppState>,
    cookies: PrivateCookieJar,
    lang_cookies: CookieJar,
    headers: HeaderMap,
    Form(form): Form<NameForm>,
) -> Response {
    let backend = &state.backend;
    let (cookies, req) = backend.client_full(cookies, &lang_cookies, &headers).await;
    let client = req.client;
    rust_i18n::set_locale(req.lang.to_locale());

    let message = match backend.set_client_name(&client, &form.name).await {
        Ok(()) => MyMessage::NameChanged,
        Err(NameUpdateError::TooShort(expected, actual)) => MyMessage::Error(
            t!("error_name_too_short_title").into(),
            t!("error_name_too_short_body", expected = expected).into(),
            format!("{}: {actual}", t!("received_characters")),
        ),
        Err(NameUpdateError::TooLong(expected, actual)) => MyMessage::Error(
            t!("error_name_too_long_title").into(),
            t!("error_name_too_long_body", expected = expected).into(),
            format!("{}: {actual}", t!("received_characters")),
        ),
        Err(NameUpdateError::ContainsBadWord) => MyMessage::Error(
            t!("error_bad_word_title").into(),
            t!("error_bad_word_body").into(),
            t!("error_bad_word_footer").into(),
        ),
    };

    retu(state, cookies, lang_cookies, headers, Some(message)).await
}

async fn ban_name(
    State(state): State<AppState>,
    private_cookies: PrivateCookieJar,
    _lang_cookies: CookieJar,
    _headers: HeaderMap,
    Form(form): Form<BanNameForm>,
) -> Response {
    // Check if user is admin
    if private_cookies.get("admin_session").is_none() {
        return axum::response::Redirect::to("/game").into_response();
    }

    let backend = &state.backend;

    // Ban the name
    let _ = backend.ban_name(&form.name).await;

    // Replace existing instances with asterisks
    let _ = backend.replace_banned_names_with_asterisks().await;

    axum::response::Redirect::to("/game").into_response()
}

pub(super) fn routes() -> Router<AppState> {
    Router::new()
        .route("/game", get(index))
        .route("/game", post(set_name))
        .route("/game/ban-name", post(ban_name))
        .route("/{*uuid}", get(game))
}
