use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Button, FileDialog, Picture, Scale, Box as GtkBox};
use image::{DynamicImage, ImageBuffer, RgbImage};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::cell::RefCell;

fn main() {
    let app = Application::builder()
        .application_id("ru.risdeveau.imageeditor")
        .build();

    app.connect_activate(|app| {
        build_ui(app);
    });

    app.run();
}

fn build_ui(app: &Application) {
    let window = ApplicationWindow::builder()
        .application(app)
        .title("Image Editor")
        .default_width(800)
        .default_height(600)
        .build();
    window.set_resizable(false);

    let container = GtkBox::new(gtk::Orientation::Vertical, 5);
    let open_button = Button::with_label("Open Image");
    let picture = Picture::new();
    let brightness_slider = Scale::with_range(gtk::Orientation::Horizontal, -100.0, 100.0, 1.0);
    brightness_slider.set_value(0.);

    // Храним путь и оригинальное изображение
    let image_data = Rc::new(RefCell::new(None::<(PathBuf, ImageBuffer<image::Rgb<u8>, Vec<u8>>)>));

    // Функция для редактирования изображения
    fn edit_image(image: &mut RgbImage, brightness: i8) {
        for pixel in image.pixels_mut() {
            pixel.0 = [
                (pixel.0[0] as i16 + brightness as i16).clamp(0, 255) as u8,
                (pixel.0[1] as i16 + brightness as i16).clamp(0, 255) as u8,
                (pixel.0[2] as i16 + brightness as i16).clamp(0, 255) as u8,
            ];
        }
    }

    // Открытие изображения
    {
        let window = window.clone();
        let image_data = image_data.clone();
        let picture = picture.clone();
        open_button.connect_clicked(move |_| {
            let dialog = FileDialog::builder()
                .title("Select Image")
                .build();

            let filter = gtk::FileFilter::new();
            filter.add_mime_type("image/*");
            dialog.set_default_filter(Some(&filter));

            let window = window.clone();
            let image_data = image_data.clone();
            let picture = picture.clone();
            dialog.open(
                Some(&window),
                None::<&gtk::gio::Cancellable>,
                move |result| {
                    if let Ok(file) = result {
                        if let Some(path) = file.path() {
                            match image::open(&path) {
                                Ok(img) => {
                                    let mut rgb_img = img.to_rgb8();
                                    *image_data.borrow_mut() = Some((path.to_path_buf(), rgb_img.clone()));
                                    
                                    // Сохраняем временную копию для отображения
                                    let temp_path = Path::new("/tmp/gtk_temp_img.png");
                                    if rgb_img.save(temp_path).is_ok() {
                                        picture.set_filename(Some(temp_path));
                                    }
                                }
                                Err(e) => eprintln!("Failed to load image: {}", e),
                            }
                        }
                    }
                }
            );
        });
    }

    // Регулировка яркости
    {
        let image_data = image_data.clone();
        let picture = picture.clone();
        brightness_slider.connect_value_changed(move |slider| {
            if let Some((path, ref mut image)) = image_data.borrow_mut().as_mut() {
                let value = slider.value() as i8;
                
                // Редактируем копию оригинального изображения
                if let Ok(original) = image::open(path) {
                    let mut edited = original.to_rgb8();
                    edit_image(&mut edited, value);
                    
                    // Сохраняем и отображаем
                    let temp_path = Path::new("/tmp/gtk_temp_img.png");
                    if edited.save(temp_path).is_ok() {
                        picture.set_filename(Some(temp_path));
                    }
                }
            }
        });
    }

    container.append(&open_button);
    container.append(&picture);
    container.append(&brightness_slider);
    window.set_child(Some(&container));
    window.show();
}
