use actix_web::{get, HttpRequest, Responder};
use maud::html;

use super::components::{build_site, video_element};

#[get("/yt/tags")]
pub async fn yt_tags(r: HttpRequest) -> impl Responder {
    let library: &actix_web::web::Data<crate::library::Library> = r.app_data().unwrap();

    let tags = library.get_tags_yt();

    let content = html!(
        h1 { (format!("†ags ({}): ", tags.len())) };
        @for tag in tags {
            a href=(format!("/yt/tag/{tag}")) {
                (tag)
            };
            br;
        };
    )
    .into_string();
    build_site(&r, "Tags", &content)
}

#[get("/yt/tag/{tag}")]
pub async fn yt_tag_page(r: HttpRequest, p: actix_web::web::Path<String>) -> impl Responder {
    let library: &actix_web::web::Data<crate::library::Library> = r.app_data().unwrap();
    let tag = p.into_inner();

    let mut channel_videos = library.get_videos_by_tag_yt(&tag);

    let video_grids: Vec<_> = channel_videos
        .chunks_mut(3)
        .map(|x| {
            html!(
                div class="grid" {
                @for video in x {
                    (video_element(video));
                };
            };
            )
        })
        .collect();

    let content = html!(
        h1 { (tag) };
        @for grid in video_grids {
            ( grid )
        };
    )
    .into_string();
    build_site(&r, &format!("#{tag}"), &content)
}

#[get("/yt/c/{channel}")]
pub async fn yt_channel_page(r: HttpRequest, p: actix_web::web::Path<String>) -> impl Responder {
    let library: &actix_web::web::Data<crate::library::Library> = r.app_data().unwrap();
    let channel_id = p.into_inner();

    let mut channel_videos = library.get_channel_videos_yt(&channel_id);
    let channel_name = library.get_channel_name_yt(&channel_id);

    let video_grids: Vec<_> = channel_videos
        .chunks_mut(3)
        .map(|x| {
            html!(
                div class="grid" {
                @for video in x {
                    (video_element(video));
                };
            };
            )
        })
        .collect();

    let content = html!(
        h1 { (channel_name) };
        @for grid in video_grids {
            ( grid )
        };
    )
    .into_string();
    build_site(&r, &channel_name, &content)
}
