use rocket::{
    form::Form,
    get,
    http::{Cookie, CookieJar},
    outcome::Outcome,
    post,
    request::{FlashMessage, FromRequest},
    response::{Flash, Redirect},
    routes,
    time::{Duration, OffsetDateTime},
    FromForm, Request, Route, State,
};
use rocket_dyn_templates::{context, tera, Template};
use sqlx::SqlitePool;

use crate::model::{
    log::Log,
    user::{LoginError, User},
};

#[get("/?<name>")]
fn index(flash: Option<FlashMessage<'_>>, name: Option<String>) -> Template {
    let mut context = tera::Context::new();

    if let Some(msg) = flash {
        context.insert("flash", &msg.into_inner());
    }

    if let Some(n) = name {
        context.insert("name", &n);
    }

    Template::render("auth/login", context.into_json())
}

#[derive(FromForm)]
struct LoginForm<'r> {
    name: &'r str,
    password: &'r str,
}

#[derive(Debug)]
pub struct UserAgent(String);

#[rocket::async_trait]
impl<'r> FromRequest<'r> for UserAgent {
    type Error = std::convert::Infallible;

    async fn from_request(
        request: &'r Request<'_>,
    ) -> rocket::request::Outcome<UserAgent, Self::Error> {
        let agent = request
            .headers()
            .get_one("User-Agent")
            .unwrap_or("Unknown")
            .to_string();
        Outcome::Success(UserAgent(agent))
    }
}

#[post("/", data = "<login>")]
async fn login(
    login: Form<LoginForm<'_>>,
    db: &State<SqlitePool>,
    cookies: &CookieJar<'_>,
    agent: UserAgent,
) -> Flash<Redirect> {
    let user = match User::login(db, login.name, login.password).await {
        Ok(user) => user,
        Err(LoginError::NoPasswordSet(user)) => {
            return Flash::warning(
                Redirect::to(format!("/auth/set-pw/{}", user.id)),
                "Setze ein neues Passwort",
            );
        }
        Err(_) => {
            return Flash::error(Redirect::to("/auth"), "Falscher Benutzername/Passwort. Du bist Vereinsmitglied und der Login klappt nicht? Kontaktiere Philipp H. (Tel.nr. siehe Signalgruppe) oder schreibe eine Mail an it@rudernlinz.at!");
        }
    };

    cookies.add_private(Cookie::new("loggedin_user", format!("{}", user.id)));

    Log::create(
        db,
        format!(
            "Succ login of {} with this useragent: {:?}",
            login.name, agent
        ),
    )
    .await;

    // Check for redirect_url cookie and redirect accordingly
    match cookies.get_private("redirect_url") {
        Some(redirect_cookie) => {
            let redirect_url = redirect_cookie.value().to_string();
            cookies.remove_private(redirect_cookie); // Remove the cookie after using it
            Flash::success(Redirect::to(redirect_url), "Login erfolgreich")
        }
        None => Flash::success(Redirect::to("/"), "Login erfolgreich"),
    }
}

#[get("/set-pw/<userid>")]
fn setpw(userid: i32) -> Template {
    Template::render("auth/set-pw", context!(userid))
}

#[derive(FromForm)]
struct UpdatePw<'r> {
    userid: i32,
    password: &'r str,
    password_confirm: &'r str,
}

#[post("/set-pw", data = "<updatepw>")]
async fn updatepw(
    db: &State<SqlitePool>,
    updatepw: Form<UpdatePw<'_>>,
    cookies: &CookieJar<'_>,
) -> Flash<Redirect> {
    let user = User::find_by_id(db, updatepw.userid).await;
    let Some(user) = user else {
        return Flash::error(
            Redirect::to("/auth"),
            format!("User with ID {} does not exist!", updatepw.userid),
        );
    };

    if updatepw.password != updatepw.password_confirm {
        return Flash::error(
            Redirect::to(format!("/auth/set-pw/{}", updatepw.userid)),
            "Passwörter stimmen nicht überein! Bitte probiere es nochmal",
        );
    }

    user.update_pw(db, updatepw.password).await;

    let mut cookie = Cookie::new("loggedin_user", format!("{}", user.id));
    cookie.set_expires(OffsetDateTime::now_utc() + Duration::weeks(12));
    cookies.add_private(cookie);

    Log::create(db, format!("User {} set her password.", user.name)).await;

    Flash::success(
        Redirect::to("/"),
        "Passwort erfolgreich gesetzt. Du bist nun eingeloggt.",
    )
}

#[get("/logout")]
fn logout(cookies: &CookieJar<'_>, _user: User) -> Flash<Redirect> {
    cookies.remove_private(Cookie::from("loggedin_user"));

    Flash::success(Redirect::to("/auth"), "Logout erfolgreich")
}

pub fn routes() -> Vec<Route> {
    routes![index, login, logout, setpw, updatepw]
}
