use crate::{Message, SettingsTab, SoftwareApp};
use cosmic::iced::{Alignment, Length};
use cosmic::{theme, widget, Element};

pub fn view(app: &SoftwareApp) -> Element<'static, Message> {
    let spacing = theme::active().cosmic().spacing;
    let tabs = widget::row::with_children(vec![
        tab_button("Updates", SettingsTab::Updates, app.settings_tab),
        tab_button("Flatpak Repositories", SettingsTab::Flatpak, app.settings_tab),
        tab_button("Firmware / LVFS", SettingsTab::Firmware, app.settings_tab),
    ])
    .spacing(spacing.space_xs);

    let body = match app.settings_tab {
        SettingsTab::Updates => updates_tab(app),
        SettingsTab::Flatpak => flatpak_tab(app),
        SettingsTab::Firmware => firmware_tab(app),
    };

    widget::column::with_children(vec![
        tabs.into(),
        widget::divider::horizontal::default().into(),
        body,
    ])
    .padding([0, spacing.space_s, spacing.space_m, spacing.space_s])
    .spacing(spacing.space_s)
    .width(Length::Fill)
    .into()
}

pub(crate) fn flatpak_add_remote_popup(app: &SoftwareApp) -> Element<'static, Message> {
    let spacing = theme::active().cosmic().spacing;
    widget::container(
        widget::column::with_children(vec![
            widget::row::with_children(vec![
                widget::text::title3("Add Flatpak Remote").into(),
                widget::space::horizontal().width(Length::Fill).into(),
                widget::button::icon(widget::icon::from_name("window-close-symbolic"))
                    .on_press(Message::CloseFlatpakAddRemote)
                    .into(),
            ])
            .align_y(Alignment::Center)
            .into(),
            widget::text::caption("Name (e.g. flathub):").into(),
            widget::text_input::text_input("remote-name", app.flatpak_new_name.clone())
                .on_input(Message::FlatpakNewNameChanged)
                .into(),
            widget::text::caption("URL (.flatpakrepo or repository URL):").into(),
            widget::text_input::text_input("https://...", app.flatpak_new_url.clone())
                .on_input(Message::FlatpakNewUrlChanged)
                .into(),
            widget::checkbox(app.flatpak_new_system)
                .label("Install as system-wide remote (recommended)")
                .on_toggle(Message::FlatpakNewSystemChanged)
                .into(),
            if app.flatpak_status.is_empty() {
                widget::space::vertical().height(Length::Fixed(1.0)).into()
            } else {
                widget::text::caption(app.flatpak_status.clone()).into()
            },
            widget::row::with_children(vec![
                widget::button::standard("Cancel")
                    .on_press(Message::CloseFlatpakAddRemote)
                    .into(),
                widget::space::horizontal().width(Length::Fill).into(),
                widget::button::suggested("Add Remote")
                    .on_press(Message::AddFlatpakRemote)
                    .into(),
            ])
            .align_y(Alignment::Center)
            .into(),
        ])
        .spacing(spacing.space_s)
        .width(Length::Fill),
    )
    .padding(spacing.space_m)
    .class(theme::Container::Dialog)
    .width(Length::Fixed(460.0))
    .into()
}

fn tab_button(label: &'static str, tab: SettingsTab, active: SettingsTab) -> Element<'static, Message> {
    if tab == active {
        widget::button::suggested(label)
            .on_press(Message::SelectSettingsTab(tab))
            .into()
    } else {
        widget::button::standard(label)
            .on_press(Message::SelectSettingsTab(tab))
            .into()
    }
}

fn updates_tab(app: &SoftwareApp) -> Element<'static, Message> {
    let spacing = theme::active().cosmic().spacing;
    let settings = &app.settings_data;
    widget::column::with_children(vec![
        widget::text::title2("Update Schedule").into(),
        widget::text::body("How often RakuOS Software checks for available updates in the background.").into(),
        widget::row::with_children(vec![
            widget::text::body("Check for updates:").into(),
            interval_button("Every 6 hours", 360, settings.update_interval),
            interval_button("Every 12 hours", 720, settings.update_interval),
            interval_button("Daily", 1440, settings.update_interval),
            interval_button("Weekly", 10080, settings.update_interval),
            interval_button("Manual only", 0, settings.update_interval),
        ])
        .spacing(spacing.space_xs)
        .align_y(Alignment::Center)
        .into(),
        widget::divider::horizontal::default().into(),
        widget::text::heading("Check for").into(),
        widget::checkbox(settings.auto_check_packages)
            .label("Overlay package updates")
            .on_toggle(Message::SettingsTogglePackages)
            .into(),
        widget::checkbox(settings.auto_check_flatpak)
            .label("Flatpak updates")
            .on_toggle(Message::SettingsToggleFlatpak)
            .into(),
        widget::checkbox(settings.auto_check_image)
            .label("System image updates (bootc)")
            .on_toggle(Message::SettingsToggleImage)
            .into(),
        widget::checkbox(settings.auto_check_appimages)
            .label("AppImage updates")
            .on_toggle(Message::SettingsToggleAppImages)
            .into(),
        widget::divider::horizontal::default().into(),
        widget::text::heading("Automatic Updates").into(),
        widget::checkbox(settings.auto_update)
            .label("Automatically install package and Flatpak updates when found")
            .on_toggle(Message::SettingsToggleAutoUpdate)
            .into(),
        widget::checkbox(app.bootc_autoupdate)
            .label("Automatically apply bootc image updates (rakuos-updater.timer)")
            .on_toggle(Message::SettingsToggleBootcAutoUpdate)
            .into(),
        widget::text::caption("System image updates always require manual approval and a reboot.").into(),
        widget::row::with_children(vec![
            widget::button::suggested("Save Settings")
                .on_press(Message::SaveSettings)
                .into(),
            if app.settings_saved {
                widget::text::caption("Settings saved").into()
            } else {
                widget::space::horizontal().width(Length::Shrink).into()
            },
        ])
        .spacing(spacing.space_s)
        .align_y(Alignment::Center)
        .into(),
    ])
    .spacing(spacing.space_s)
    .width(Length::Fill)
    .into()
}

fn flatpak_tab(app: &SoftwareApp) -> Element<'static, Message> {
    let spacing = theme::active().cosmic().spacing;
    let mut rows: Vec<Element<_>> = vec![
        widget::container(
            widget::row::with_children(vec![
                widget::column::with_children(vec![
                    widget::text::title2("Flatpak Repositories").into(),
                    widget::text::body("Manage Flatpak repositories. System remotes are available to all users.").into(),
                ])
                .width(Length::Fill)
                .into(),
                if app.flatpak_has_flathub {
                    widget::text::caption("Flathub configured").into()
                } else {
                    widget::button::suggested("Add Flathub")
                        .on_press(Message::AddFlathub)
                        .into()
                },
                widget::button::standard("Add Remote")
                    .on_press(Message::OpenFlatpakAddRemote)
                    .into(),
            ])
            .spacing(spacing.space_s)
            .align_y(Alignment::Center),
        )
        .padding(spacing.space_s)
        .class(theme::Container::Card)
        .width(Length::Fill)
        .into(),
    ];

    if !app.flatpak_status.is_empty() {
        rows.push(widget::text::caption(app.flatpak_status.clone()).into());
    }

    if app.flatpak_remotes.is_empty() {
        rows.push(widget::text::caption("No Flatpak remotes configured.").into());
    } else {
        for remote in &app.flatpak_remotes {
            rows.push(flatpak_remote_row(remote));
        }
    }

    widget::column::with_children(rows)
        .spacing(spacing.space_s)
        .width(Length::Fill)
        .into()
}

fn firmware_tab(app: &SoftwareApp) -> Element<'static, Message> {
    let spacing = theme::active().cosmic().spacing;
    let data = &app.firmware_data;
    let mut rows: Vec<Element<_>> = vec![
        widget::container(
            widget::row::with_children(vec![
                widget::column::with_children(vec![
                    widget::text::title2("Firmware & LVFS").into(),
                    widget::text::body("Manage firmware update sources via fwupd. LVFS provides updates from hardware vendors.").into(),
                ])
                .width(Length::Fill)
                .into(),
                if app.firmware_refreshing {
                    widget::text::caption("Refreshing...").into()
                } else {
                    widget::button::standard("Refresh Metadata")
                        .on_press(Message::RefreshFirmware)
                        .into()
                },
            ])
            .spacing(spacing.space_s)
            .align_y(Alignment::Center),
        )
        .padding(spacing.space_s)
        .class(theme::Container::Card)
        .width(Length::Fill)
        .into(),
    ];

    if !app.firmware_status.is_empty() {
        rows.push(widget::text::caption(app.firmware_status.clone()).into());
    }

    if !data.available {
        rows.push(widget::text::body("fwupd is not installed. Install it to manage firmware updates.").into());
    } else {
        rows.push(widget::text::heading("Remotes").into());
        if data.remotes.is_empty() {
            rows.push(widget::text::caption("No firmware remotes configured.").into());
        } else {
            for remote in &data.remotes {
                rows.push(firmware_remote_row(remote));
            }
        }

        rows.push(widget::text::heading(format!("Vendor Directories ({} found)", data.vendor_dirs.len())).into());
        if data.vendor_dirs.is_empty() {
            rows.push(widget::text::caption("No vendor directories found.").into());
        } else {
            for remote in &data.vendor_dirs {
                rows.push(vendor_remote_row(remote));
            }
        }

        rows.push(widget::text::heading("Available firmware updates").into());
        if data.updates.is_empty() {
            rows.push(widget::text::caption("No firmware updates reported.").into());
        } else {
            for update in &data.updates {
                rows.push(widget::text::body(update.to_string()).into());
            }
        }
    }

    widget::column::with_children(rows)
        .spacing(spacing.space_s)
        .width(Length::Fill)
        .into()
}

fn interval_button(label: &'static str, value: u32, current: u32) -> Element<'static, Message> {
    if current == value {
        widget::button::suggested(label)
            .on_press(Message::SettingsInterval(value))
            .into()
    } else {
        widget::button::standard(label)
            .on_press(Message::SettingsInterval(value))
            .into()
    }
}

fn flatpak_remote_row(remote: &rakuos_flatpak::FlatpakRemote) -> Element<'static, Message> {
    let spacing = theme::active().cosmic().spacing;
    let name = remote.name.clone();
    let toggle_name = remote.name.clone();
    let remove_name = remote.name.clone();
    let title = if remote.title.is_empty() { remote.name.clone() } else { remote.title.clone() };
    let scope = if remote.system { "system" } else { "user" };
    let system = remote.system;

    widget::container(
        widget::row::with_children(vec![
            widget::checkbox(remote.enabled)
                .label(title)
                .on_toggle(move |enabled| Message::ToggleFlatpakRemote(toggle_name.clone(), enabled, system))
                .into(),
            widget::column::with_children(vec![
                widget::text::caption(format!("{scope} remote: {name}")).into(),
                widget::text::caption(remote.url.clone()).into(),
            ])
            .width(Length::Fill)
            .into(),
            widget::button::destructive("Remove")
                .on_press(Message::RemoveFlatpakRemote(remove_name, system))
                .into(),
        ])
        .spacing(spacing.space_s)
        .align_y(Alignment::Center),
    )
    .padding(spacing.space_s)
    .class(theme::Container::Card)
    .width(Length::Fill)
    .into()
}

fn firmware_remote_row(remote: &rakuos_firmware::FwupdRemote) -> Element<'static, Message> {
    let spacing = theme::active().cosmic().spacing;
    let toggle_id = remote.id.clone();
    widget::container(
        widget::row::with_children(vec![
            widget::checkbox(remote.enabled)
                .label(if remote.title.is_empty() { remote.id.clone() } else { remote.title.clone() })
                .on_toggle(move |enabled| Message::ToggleFirmwareRemote(toggle_id.clone(), enabled))
                .into(),
            widget::column::with_children(vec![
                widget::text::caption(remote.kind.clone()).into(),
                widget::text::caption(remote.url.clone()).into(),
                widget::text::caption(if remote.last_updated.is_empty() {
                    String::new()
                } else {
                    format!("Updated: {}", remote.last_updated)
                })
                .into(),
            ])
            .width(Length::Fill)
            .into(),
        ])
        .spacing(spacing.space_s)
        .align_y(Alignment::Center),
    )
    .padding(spacing.space_s)
    .class(theme::Container::Card)
    .width(Length::Fill)
    .into()
}

fn vendor_remote_row(remote: &rakuos_firmware::FwupdRemote) -> Element<'static, Message> {
    let spacing = theme::active().cosmic().spacing;
    widget::container(
        widget::column::with_children(vec![
            widget::text::heading(if remote.title.is_empty() { remote.id.clone() } else { remote.title.clone() }).into(),
            widget::text::caption(remote.filename.clone()).into(),
        ])
        .spacing(spacing.space_xxs),
    )
    .padding(spacing.space_s)
    .class(theme::Container::Card)
    .width(Length::Fill)
    .into()
}
