use super::common;
use crate::{local_file_action_label, Message, SoftwareApp, ICON_SIZE_DETAIL};
use cosmic::iced::{Alignment, Length};
use cosmic::{theme, widget, Element};

pub fn view(app: &SoftwareApp) -> Element<'_, Message> {
    let spacing = theme::active().cosmic().spacing;
    let Some(local) = &app.local_file else {
        return super::common::message_page("Install Local File", "No local file selected.");
    };

    let mut column = widget::column::with_capacity(10)
        .padding([0, spacing.space_s, spacing.space_m, spacing.space_s])
        .spacing(spacing.space_m)
        .width(Length::Fill);

    column = column.push(
        widget::button::text("Back")
            .leading_icon(widget::icon::from_name("go-previous-symbolic").size(16))
            .on_press(Message::CloseLocalFile),
    );

    if local.loading {
        return column
            .push(widget::text::title2("Install Local File"))
            .push(widget::text::body("Reading package metadata..."))
            .into();
    }

    let info = local.info.as_ref();
    let name = info
        .and_then(|value| value["name"].as_str())
        .filter(|value| !value.is_empty())
        .unwrap_or(&local.path);
    let version = info
        .and_then(|value| value["version"].as_str())
        .unwrap_or_default();
    let summary = info
        .and_then(|value| value["summary"].as_str())
        .unwrap_or_default();
    let description = info
        .and_then(|value| value["description"].as_str())
        .unwrap_or_default();
    let icon_path = info
        .and_then(|value| value["icon_path"].as_str())
        .unwrap_or_default();
    let icon_url = info
        .and_then(|value| value["icon_url"].as_str())
        .unwrap_or_default();
    let installed = info
        .and_then(|value| value["installed"].as_bool())
        .unwrap_or(false);
    let action = info
        .and_then(|value| value["install_action"].as_str())
        .unwrap_or(if installed { "reinstall" } else { "install" });

    let install_label = if local.installing {
        "Installing...".to_string()
    } else if local.success {
        "Done".to_string()
    } else {
        local_file_action_label(action).to_string()
    };

    column = column.push(
        widget::row::with_children(vec![
            common::app_icon(icon_path, icon_url, ICON_SIZE_DETAIL),
            widget::column::with_children(vec![
                widget::text::title2(name).into(),
                if version.is_empty() {
                    widget::space::vertical().height(Length::Fixed(1.0)).into()
                } else {
                    widget::text::caption(version).into()
                },
                if summary.is_empty() {
                    widget::space::vertical().height(Length::Fixed(1.0)).into()
                } else {
                    widget::text::body(summary).into()
                },
            ])
            .spacing(spacing.space_xxs)
            .width(Length::Fill)
            .into(),
            if local.installing || local.success {
                widget::button::standard(install_label).into()
            } else {
                widget::button::suggested(install_label)
                    .on_press(Message::InstallLocalFile)
                    .into()
            },
        ])
        .spacing(spacing.space_m)
        .align_y(Alignment::Center),
    );

    column = column.push(widget::text::caption(local.path.clone()));

    if !description.trim().is_empty() {
        column = column
            .push(widget::text::title4("Description"))
            .push(widget::text::body(description));
    }

    if !local.status.is_empty() {
        column = column.push(widget::text::body(local.status.clone()));
    }

    if !local.log.trim().is_empty() {
        column = column
            .push(widget::text::title4("Install Log"))
            .push(
                widget::container(widget::text::caption(local.log.clone()))
                    .padding(spacing.space_s)
                    .width(Length::Fill)
                    .class(theme::Container::Card),
            );
    }

    column.into()
}
