use super::detail::SeasonItem;
use super::library::ShowLibraryItem;
use crate::ui::Message;
use crate::ui::shared::cover::{watched_toggle_button, watched_toggle_compact};
use crate::ui::shared::styles::{self, BG_CARD, GRAY_50, GRAY_70};
use iced::Element;

pub(crate) struct EpisodeItem {
    pub(crate) id: i64,
    pub(crate) episode_number: i64,
    pub(crate) title: Option<String>,
    pub(crate) file: String,
    pub(crate) watched: bool,
    pub(crate) playback_position: Option<f64>,
}

pub(crate) fn view<'a>(
    show: &'a ShowLibraryItem,
    season: &'a SeasonItem,
    episodes: &'a [EpisodeItem],
    last_played_file: Option<&str>,
    ui_scale: f32,
) -> Element<'a, Message> {
    let season_label = season
        .title
        .clone()
        .unwrap_or_else(|| format!("Season {}", season.season_number));

    let header_title = iced::widget::text(show.title.clone())
        .size(styles::TEXT_SIZE_TITLE * ui_scale)
        .color(iced::Color::WHITE);

    let season_title = iced::widget::text(season_label)
        .size(styles::TEXT_SIZE_SUBSECTION * ui_scale)
        .color(GRAY_70);

    let episode_count = iced::widget::text(format!("{} episode(s)", episodes.len()))
        .size(styles::CARD_LABEL_SIZE * ui_scale)
        .color(GRAY_50);

    let watched_btn = watched_toggle_button(season.watched, Message::ToggleSeasonWatched, ui_scale);

    let mut header = iced::widget::column![header_title, season_title, episode_count]
        .spacing(styles::SPACING_DEFAULT);
    if let Some(rd) =
        styles::rating_and_description(season.rating, season.description.as_deref(), ui_scale)
    {
        header = header.push(rd);
    }
    let header = header.push(watched_btn);

    let mut episode_list = iced::widget::column![].spacing(styles::SPACING_TIGHT);

    for (ep_index, ep) in episodes.iter().enumerate() {
        let is_last_played = last_played_file.is_some_and(|f| f == ep.file);

        let ep_title = ep.title.as_deref().unwrap_or("Untitled");

        let label = iced::widget::text(format!("E{:02}  {}", ep.episode_number, ep_title))
            .size(styles::CARD_LABEL_SIZE * ui_scale)
            .color(if is_last_played {
                iced::Color::from_rgb(1.0, 0.4, 0.4)
            } else {
                iced::Color::WHITE
            });

        let play_btn = styles::play_button(Message::PlayEpisode(ep.file.clone()), ui_scale);

        let bg_color = if is_last_played {
            iced::Color::from_rgb(0.2, 0.1, 0.1)
        } else if ep.watched {
            iced::Color::from_rgb(0.1, 0.18, 0.1)
        } else {
            BG_CARD
        };

        let file_clone = ep.file.clone();
        let row = iced::widget::mouse_area(
            iced::widget::container(
                iced::widget::row![
                    label,
                    iced::widget::Space::new().width(iced::Length::Fill),
                    watched_toggle_compact(
                        ep.watched,
                        Message::ToggleEpisodeWatched(ep_index),
                        ui_scale
                    ),
                    play_btn
                ]
                .spacing(styles::SPACING_MEDIUM)
                .align_y(iced::Alignment::Center)
                .padding(iced::Padding::from([8.0, 12.0])),
            )
            .style(move |_theme| iced::widget::container::Style {
                background: Some(iced::Background::Color(bg_color)),
                border: iced::border::rounded(styles::RADIUS_STANDARD),
                ..Default::default()
            }),
        )
        .on_press(Message::PlayEpisode(file_clone));

        episode_list = episode_list.push(row);
    }

    let content = iced::widget::column![header, episode_list]
        .spacing(styles::SPACING_LARGE)
        .padding(iced::Padding::new(styles::PADDING_LARGE))
        .max_width(900.0 * ui_scale);

    iced::widget::scrollable(content)
        .width(iced::Length::Fill)
        .height(iced::Length::Fill)
        .into()
}
