use super::Message as MovieMessage;
use super::library::LibraryItem;
use crate::ui::Message;
use crate::ui::shared::cover::watched_toggle_button;
use crate::ui::shared::styles::{self, GRAY_40, GRAY_60, GRAY_70, GRAY_80};
use iced::Element;

const COVER_WIDTH: f32 = 200.0;
const COVER_HEIGHT: f32 = 300.0;

pub(crate) fn view<'a>(
    item: &'a LibraryItem,
    movie_index: usize,
    tmdb_widget: Option<Element<'a, Message>>,
    ui_scale: f32,
) -> Element<'a, Message> {
    let cover_w = COVER_WIDTH * ui_scale;
    let cover_h = COVER_HEIGHT * ui_scale;

    let year_str = item.release_year.map(|y| y.to_string()).unwrap_or_default();

    let cover_image: Element<_> = if let Some(path) = &item.cover_path {
        iced::widget::image(iced::widget::image::Handle::from_path(path))
            .width(cover_w)
            .height(cover_h)
            .into()
    } else {
        iced::widget::container(
            iced::widget::text("No Cover")
                .size(styles::TEXT_SIZE_BODY * ui_scale)
                .color(GRAY_40),
        )
        .width(cover_w)
        .height(cover_h)
        .center_x(cover_w)
        .center_y(cover_h)
        .style(styles::placeholder_style)
        .into()
    };

    let cover = styles::cover_with_border_shadow(cover_image);

    let title = iced::widget::text(&item.title)
        .size(styles::TEXT_SIZE_TITLE * ui_scale)
        .color(iced::Color::WHITE);

    let play_button = styles::play_button_large(Message::PlayMovie(movie_index), ui_scale);
    let watched_btn = watched_toggle_button(
        item.watched,
        Message::Movie(MovieMessage::ToggleWatched(movie_index)),
        ui_scale,
    );

    let has_backdrop = item.backdrop_path.is_some();
    let (year_color, file_color, gap_height) = if has_backdrop {
        (GRAY_80, GRAY_70, 8.0)
    } else {
        (GRAY_60, GRAY_40, 12.0)
    };

    let mut info = iced::widget::column![title].spacing(styles::SPACING_DEFAULT);

    if !year_str.is_empty() {
        info = info.push(
            iced::widget::text(year_str)
                .size(styles::TEXT_SIZE_BODY * ui_scale)
                .color(year_color),
        );
    }

    if let Some(rd) =
        styles::rating_and_description(item.rating, item.description.as_deref(), ui_scale)
    {
        info = info.push(rd);
    }

    info = info.push(
        iced::widget::text(&item.file)
            .size(styles::TEXT_SIZE_SMALL * ui_scale)
            .color(file_color),
    );

    info = info
        .push(iced::widget::Space::new().height(gap_height))
        .push(iced::widget::row![play_button, watched_btn].spacing(styles::SPACING_DEFAULT));

    let extras: Vec<Element<Message>> = tmdb_widget.into_iter().collect();
    styles::detail_layout(cover, info.into(), extras, item.backdrop_path.as_deref())
}
