package org.example.petshopdesktop.util;

import javafx.stage.FileChooser;
import javafx.stage.Window;

import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.Component;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicReference;

public final class FilePickerSupport {

    private FilePickerSupport() {
    }

    public static File pickImageFile(Window ownerWindow) {
        if (shouldUseAwtPicker()) {
            return pickImageFileWithSwing();
        }
        return pickImageFileWithJavaFx(ownerWindow);
    }

    public static File pickAnyFile(Window ownerWindow) {
        if (shouldUseAwtPicker()) {
            return pickAnyFileWithSwing();
        }
        return pickAnyFileWithJavaFx(ownerWindow);
    }

    private static boolean shouldUseAwtPicker() {
        if (GraphicsEnvironment.isHeadless()) {
            return false;
        }
        String sessionType = System.getenv("XDG_SESSION_TYPE");
        String waylandDisplay = System.getenv("WAYLAND_DISPLAY");
        return "wayland".equalsIgnoreCase(sessionType) || (waylandDisplay != null && !waylandDisplay.isBlank());
    }

    private static File pickImageFileWithJavaFx(Window ownerWindow) {
        FileChooser chooser = new FileChooser();
        chooser.setTitle("Choose Profile Picture");
        chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.jpeg", "*.gif"));
        return chooser.showOpenDialog(ownerWindow);
    }

    private static File pickAnyFileWithJavaFx(Window ownerWindow) {
        FileChooser chooser = new FileChooser();
        chooser.setTitle("Choose File Attachment");
        return chooser.showOpenDialog(ownerWindow);
    }

    private static File pickImageFileWithSwing() {
        AtomicReference<File> selectedFile = new AtomicReference<>();
        Runnable dialogTask = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception ignored) {
            }

            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("Choose Profile Picture");
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.setFileFilter(new FileNameExtensionFilter("Image Files", "png", "jpg", "jpeg", "gif"));

            int result = chooser.showOpenDialog((Component) null);
            if (result == JFileChooser.APPROVE_OPTION) {
                selectedFile.set(chooser.getSelectedFile());
            }
        };

        try {
            if (java.awt.EventQueue.isDispatchThread()) {
                dialogTask.run();
            } else {
                java.awt.EventQueue.invokeAndWait(dialogTask);
            }
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            return null;
        } catch (InvocationTargetException ex) {
            throw new IllegalStateException("Failed to open Swing file picker", ex.getCause());
        }

        return selectedFile.get();
    }

    private static File pickAnyFileWithSwing() {
        AtomicReference<File> selectedFile = new AtomicReference<>();
        Runnable dialogTask = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception ignored) {
            }

            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("Choose File Attachment");
            chooser.setAcceptAllFileFilterUsed(true);

            int result = chooser.showOpenDialog((Component) null);
            if (result == JFileChooser.APPROVE_OPTION) {
                selectedFile.set(chooser.getSelectedFile());
            }
        };

        try {
            if (java.awt.EventQueue.isDispatchThread()) {
                dialogTask.run();
            } else {
                java.awt.EventQueue.invokeAndWait(dialogTask);
            }
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            return null;
        } catch (InvocationTargetException ex) {
            throw new IllegalStateException("Failed to open Swing file picker", ex.getCause());
        }

        return selectedFile.get();
    }
}
