use druid::{
    AppDelegate, AppLauncher, Data, Env, Event, EventCtx, Lens, LocalizedString, Menu, MenuItem,
    RenderContext, Widget, WidgetExt, WindowDesc,
};
use rand::Rng;
use std::sync::Arc;

#[derive(Clone, Data, Lens)]
struct AppState {
    items: String,
    selected_item: String,
}

fn main() {
    let main_window = WindowDesc::new(build_ui)
        .title(LocalizedString::new("Wheel of Fortune"))
        .window_size((300.0, 150.0));

    let initial_state = AppState {
        items: String::new(),
        selected_item: String::new(),
    };

    AppLauncher::with_window(main_window)
        .delegate(Delegate {})
        .launch(initial_state)
        .expect("Failed to launch application");
}

fn build_ui() -> impl Widget<AppState> {
    use druid::widget::{Button, Column, TextBox};

    let input = TextBox::new().lens(AppState::items);

    let spin_button = Button::new("Spin")
        .on_click(|ctx, data: &mut AppState, _env| {
            let items = data.items.split(',').collect::<Vec<&str>>();
            let selected_item = match items.choose(&mut rand::thread_rng()) {
                Some(&item) => item.to_string(),
                None => String::new(),
            };
            data.selected_item = selected_item.clone();
            ctx.request_paint();
        })
        .fix_height(40.0);

    let result_label = druid::widget::Label::new(|data: &AppState, _env: &Env| {
        if data.selected_item.is_empty() {
            "Selected Item: (none)".to_string()
        } else {
            format!("Selected Item: {}", data.selected_item)
        }
    });

    Column::new()
        .spacing(10.0)
        .padding(10.0)
        .align_vertical(druid::widget::Align::Center)
        .add_child(input)
        .add_child(spin_button)
        .add_child(result_label)
}
