use super::styles::{
    ACCENT_RED, BG_BREADCRUMB, BG_INPUT, BG_INPUT_INACTIVE, BG_TAB_BAR, GRAY_25, GRAY_35, GRAY_40,
    GRAY_50, GRAY_70, GRAY_90,
};
use crate::ui::Message;
use iced::Element;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Tab {
    Home,
    Movies,
    TvShows,
}

#[derive(Debug, Clone)]
pub(crate) enum BreadcrumbNav {
    MovieLibrary,
    ShowLibrary,
    ShowDetail { show_index: usize },
}

pub(crate) const SEARCH_INPUT_ID: &str = "search-input";

const SPINNER_GLYPHS: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];

pub(crate) fn tab_bar(
    active: Tab,
    search_query: &str,
    scanning: bool,
    spinner_frame: usize,
) -> Element<'static, Message> {
    let home_btn = tab_button("Home", Tab::Home, active);
    let movies_btn = tab_button("Movies", Tab::Movies, active);
    let shows_btn = tab_button("TV Shows", Tab::TvShows, active);

    let has_text = !search_query.is_empty();
    let search_input = iced::widget::container(
        iced::widget::text_input("Search...", search_query)
            .id(SEARCH_INPUT_ID)
            .on_input(Message::SearchQueryChanged)
            .size(13)
            .width(300)
            .style(move |_theme, status| {
                let is_active =
                    has_text || matches!(status, iced::widget::text_input::Status::Focused { .. });
                iced::widget::text_input::Style {
                    background: iced::Background::Color(if is_active {
                        BG_INPUT
                    } else {
                        BG_INPUT_INACTIVE
                    }),
                    border: iced::Border {
                        color: if is_active { ACCENT_RED } else { GRAY_25 },
                        width: 1.0,
                        radius: 4.0.into(),
                    },
                    icon: GRAY_50,
                    placeholder: GRAY_40,
                    value: GRAY_90,
                    selection: iced::Color::from_rgb(0.3, 0.3, 0.5),
                }
            }),
    )
    .padding(iced::Padding::from([0.0, 16.0]))
    .align_y(iced::Alignment::Center);

    iced::widget::container(
        iced::widget::row![
            home_btn,
            movies_btn,
            shows_btn,
            iced::widget::Space::new().width(iced::Length::Fill),
            search_input,
            iced::widget::button(
                iced::widget::text(if scanning {
                    SPINNER_GLYPHS[spinner_frame % SPINNER_GLYPHS.len()].to_string()
                } else {
                    "Scan".to_string()
                })
                .size(12)
                .color(GRAY_50),
            )
            .on_press(if scanning {
                Message::CancelScan
            } else {
                Message::StartScan
            })
            .padding(iced::Padding::from([6.0, 12.0]))
            .style(|_theme, status| {
                let text_color = match status {
                    iced::widget::button::Status::Hovered => GRAY_70,
                    _ => GRAY_50,
                };
                iced::widget::button::Style {
                    background: None,
                    text_color,
                    ..Default::default()
                }
            }),
            iced::widget::button(
                iced::widget::text("Logs".to_string())
                    .size(12)
                    .color(GRAY_50),
            )
            .on_press(Message::OpenLogs)
            .padding(iced::Padding::from([6.0, 12.0]))
            .style(|_theme, status| {
                let text_color = match status {
                    iced::widget::button::Status::Hovered => GRAY_70,
                    _ => GRAY_50,
                };
                iced::widget::button::Style {
                    background: None,
                    text_color,
                    ..Default::default()
                }
            }),
        ]
        .spacing(0)
        .align_y(iced::Alignment::Center)
        .padding(iced::Padding::from([0.0, 16.0])),
    )
    .width(iced::Length::Fill)
    .style(|_theme| iced::widget::container::Style {
        background: Some(iced::Background::Color(BG_TAB_BAR)),
        ..Default::default()
    })
    .into()
}

fn tab_button(label: &str, tab: Tab, active: Tab) -> Element<'static, Message> {
    let is_active = tab == active;

    let text = iced::widget::text(label.to_string())
        .size(14)
        .color(if is_active {
            iced::Color::WHITE
        } else {
            GRAY_50
        });

    let underline = iced::widget::container(iced::widget::Space::new().height(2))
        .width(iced::Length::Fill)
        .style(move |_theme| iced::widget::container::Style {
            background: if is_active {
                Some(iced::Background::Color(ACCENT_RED))
            } else {
                None
            },
            ..Default::default()
        });

    let content = iced::widget::column![text, underline]
        .align_x(iced::Alignment::Center)
        .spacing(6);

    iced::widget::button(content)
        .on_press(Message::SwitchTab(tab))
        .padding(iced::Padding::new(10.0).bottom(4.0).left(20.0).right(20.0))
        .style(|_theme, status| {
            let bg = match status {
                iced::widget::button::Status::Hovered => iced::Color::from_rgb(0.14, 0.14, 0.14),
                _ => iced::Color::TRANSPARENT,
            };
            iced::widget::button::Style {
                background: Some(iced::Background::Color(bg)),
                text_color: iced::Color::WHITE,
                ..Default::default()
            }
        })
        .into()
}

pub(crate) fn breadcrumb(
    segments: Vec<(String, Option<BreadcrumbNav>)>,
    ui_scale: f32,
) -> Element<'static, Message> {
    let mut row = iced::widget::row![]
        .spacing(0)
        .align_y(iced::Alignment::Center);

    for (i, (label, target)) in segments.into_iter().enumerate() {
        if i > 0 {
            row = row.push(
                iced::widget::text("  >  ")
                    .size(12.0 * ui_scale)
                    .color(GRAY_35),
            );
        }

        let element: Element<_> = if let Some(nav) = target {
            iced::widget::button(
                iced::widget::text(label)
                    .size(13.0 * ui_scale)
                    .color(GRAY_50),
            )
            .on_press(Message::NavigateBreadcrumb(nav))
            .padding(iced::Padding::from([2.0, 4.0]))
            .style(|_theme, status| {
                let text_color = match status {
                    iced::widget::button::Status::Hovered => GRAY_70,
                    _ => GRAY_50,
                };
                iced::widget::button::Style {
                    background: None,
                    text_color,
                    ..Default::default()
                }
            })
            .into()
        } else {
            iced::widget::text(label)
                .size(13.0 * ui_scale)
                .color(GRAY_70)
                .into()
        };

        row = row.push(element);
    }

    iced::widget::container(row.padding(iced::Padding::from([6.0, 20.0])))
        .width(iced::Length::Fill)
        .style(|_theme| iced::widget::container::Style {
            background: Some(iced::Background::Color(BG_BREADCRUMB)),
            ..Default::default()
        })
        .into()
}
