package cz.kamma.llamarunner;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * Reusable dialog for simple text input.
 */
public class InputDialog {

    private final JDialog dialog;
    private final String[] result = new String[1];

    /**
     * Shows a dialog for text input.
     *
     * @param parent the parent frame
     * @param title the dialog title
     * @param label the label text
     * @param defaultValue the default value
     * @return the input text, or null if cancelled
     */
    public static String showInputDialog(java.awt.Frame parent, String title, String label, String defaultValue) {
        InputDialog dialog = new InputDialog(parent, title, label, defaultValue);
        dialog.show();
        return dialog.getResult();
    }

    private InputDialog(java.awt.Frame parent, String title, String label, String defaultValue) {
        dialog = new JDialog(parent, title, true);
        dialog.setResizable(false);

        // Input panel
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(4, 4, 4, 4);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(new JLabel(label), gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        JTextField textField = new JTextField(20);
        textField.setText(defaultValue);
        textField.setCaretColor(Color.WHITE);
        inputPanel.add(textField, gbc);

        dialog.add(inputPanel, BorderLayout.CENTER);

        // Button panel
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 0));
        JButton okButton = new JButton("OK");
        okButton.addActionListener(e -> {
            result[0] = textField.getText().trim();
            dialog.dispose();
        });
        buttonPanel.add(okButton);

        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(e -> {
            result[0] = null;
            dialog.dispose();
        });
        buttonPanel.add(cancelButton);

        dialog.add(buttonPanel, BorderLayout.SOUTH);

        // Center dialog
        dialog.setSize(350, 100);
        dialog.setLocationRelativeTo(parent);
    }

    private void show() {
        dialog.setVisible(true);
    }

    private String getResult() {
        if (result[0] == null) {
            return null;
        }
        return result[0].isEmpty() ? null : result[0];
    }
}
