use based::{
    auth::MaybeUser,
    format::format_date,
    request::{RequestContext, StringResponse},
};
use maud::html;
use rocket::{get, State};

use crate::{
    library::{history::VideoHistory, Library},
    pages::components::video_element_wide,
};

use super::components::render_page;

#[get("/watch?<v>")]
pub async fn watch_page(
    ctx: RequestContext,
    library: &State<Library>,
    v: String,
    user: MaybeUser,
) -> StringResponse {
    let video = if let Some(video) = library.get_video_by_id(&v).await {
        video
    } else {
        // TODO : Error handling
        library.get_video_by_youtube_id(&v).await.unwrap()
    };

    if let Some(user) = user.user() {
        user.insert_history(video.id).await;
    }

    let content = html!(
        main class="container mx-auto mt-6 flex flex-col lg:flex-row gap-6" {
          div class="lg:w-10/12 mt-10" {
            div class="bg-black aspect-video rounded-lg overflow-hidden" {
              video
                controls
                autoplay
                class="w-full h-full" {
                source src=(format!("/video/raw?v={}", video.id)) type="video/mp4" {
                    "Your browser does not support the video"
                };
            };
            };
            div class="p-4 bg-stone-900 rounded-lg shadow-lg mt-8" {
              h2 class="text-2xl font-semibold" { (video.title) };

              @if let Some(meta) = video.youtube_meta().await {
                div class="flex justify-between mt-2" {
                  p class="mb-4 text-gray-300" { (meta.uploader_name) };
                  p class="mb-4 text-gray-300" { (format!("{} Views ﹣ {}", meta.views, format_date(&meta.upload_date))) };
                };

                a href=(format!("https://www.youtube.com/watch?v={}", meta.id)) class="text-blue-400" {"Watch on YouTube" };

                p class="mb-2 text-gray-300 text-bold mt-2" { "Description: " } span { (meta.description) };
              };

            };
          };
          div id="recommendations" class="mt-8 w-1/3" {
            h3 class="text-center text-4xl font-extrabold leading-tight mb-2" { "In " a class="text-blue-500" href=(format!("/d/{}", video.directory)) { (video.directory) }; }
            @for video in library.get_directory_videos(&video.directory).await {
              (video_element_wide(&video).await);
            };
          };
        };
    );

    render_page(
        ctx,
        content,
        &format!("{} - WatchDogs", video.title),
        user.into(),
    )
    .await
}