// BuyerGUI.java
package ld5_2;
 
import jade.gui.GuiEvent;
import ld5_2.ontology.*;
 
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
 
public class BuyerGUI extends JFrame {
 
    private final Buyer agent;
 
    private final JTextField tfPriceFrom = new JTextField("0",      7);
    private final JTextField tfPriceTo   = new JTextField("100000", 7);
    private final JTextField tfYearFrom  = new JTextField("2000",   5);
    private final JTextField tfYearTo    = new JTextField("2025",   5);
    private final JTextField tfCountry   = new JTextField("Japan",  10);
 
    private final String[] COLS = {
        "VIN", "Make", "Model", "Modif.", "Color", "Engine", "Year", "Cost (€)"
    };
    private final DefaultTableModel tableModel = new DefaultTableModel(COLS, 0) {
        @Override public boolean isCellEditable(int r, int c) { return false; }
        @Override public Class<?> getColumnClass(int c) {
            return (c == 0 || c == 6 || c == 7) ? Integer.class : String.class;
        }
    };
    private final JTable table = new JTable(tableModel);
    private final JLabel lblStatus = new JLabel("enter filters and search.");
 
    public BuyerGUI(Buyer agent) {
        this.agent = agent;
        setTitle("Buyer " + agent.getLocalName());
        setSize(900, 520);
        setMinimumSize(new Dimension(700, 400));
        setLocationRelativeTo(null);
 
        // Uždarius langą – sustabdyti agentą
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override public void windowClosing(java.awt.event.WindowEvent e) {
                agent.doDelete();
            }
        });
 
        buildUI();
    }
 
    private void buildUI() {
        setLayout(new BorderLayout(6, 6));
 
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 6));
        searchPanel.setBorder(new TitledBorder("filters"));
 
        searchPanel.add(new JLabel("cost €:"));
        searchPanel.add(tfPriceFrom);
        searchPanel.add(new JLabel("-"));
        searchPanel.add(tfPriceTo);
        searchPanel.add(Box.createHorizontalStrut(12));
 
        searchPanel.add(new JLabel("year:"));
        searchPanel.add(tfYearFrom);
        searchPanel.add(new JLabel("–"));
        searchPanel.add(tfYearTo);
        searchPanel.add(Box.createHorizontalStrut(12));
 
        searchPanel.add(new JLabel("Country:"));
        searchPanel.add(tfCountry);
        searchPanel.add(Box.createHorizontalStrut(16));
 
        JButton btnSearch = new JButton("search");
        styleButton(btnSearch, new Color(70, 130, 180));
        searchPanel.add(btnSearch);
        btnSearch.addActionListener(e -> onSearch());
 
        add(searchPanel, BorderLayout.NORTH);
 
        table.setRowHeight(22);
        table.setAutoCreateRowSorter(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.getTableHeader().setReorderingAllowed(false);
 
        int[] colWidths = {55, 90, 90, 80, 70, 75, 55, 80};
        for (int i = 0; i < colWidths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(colWidths[i]);
        }
 
        JScrollPane scroll = new JScrollPane(table);
        scroll.setBorder(new TitledBorder("cars found"));
        add(scroll, BorderLayout.CENTER);
 
        JPanel bottomPanel = new JPanel(new BorderLayout(4, 4));
 
        JPanel buyPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 4));
        buyPanel.setBorder(new TitledBorder("Buy"));
 
        JButton btnBuy = new JButton("Buy selected");
        styleButton(btnBuy, new Color(34, 139, 34));
        buyPanel.add(btnBuy);
        buyPanel.add(new JLabel("select"));
        btnBuy.addActionListener(e -> onBuy());
 
        lblStatus.setBorder(BorderFactory.createEmptyBorder(2, 10, 4, 0));
        lblStatus.setFont(lblStatus.getFont().deriveFont(Font.ITALIC));
 
        bottomPanel.add(buyPanel, BorderLayout.NORTH);
        bottomPanel.add(lblStatus, BorderLayout.SOUTH);
        add(bottomPanel, BorderLayout.SOUTH);
    }
 
    private void onSearch() {
        try {
            int priceFrom = Integer.parseInt(tfPriceFrom.getText().trim());
            int priceTo   = Integer.parseInt(tfPriceTo  .getText().trim());
            int yearFrom  = Integer.parseInt(tfYearFrom .getText().trim());
            int yearTo    = Integer.parseInt(tfYearTo   .getText().trim());
            String country = tfCountry.getText().trim();
 
            tableModel.setRowCount(0);
            setStatus("searching...", true);
 
            GuiEvent ge = new GuiEvent(this, Buyer.SEARCH_EVENT);
            ge.addParameter(priceFrom);
            ge.addParameter(priceTo);
            ge.addParameter(yearFrom);
            ge.addParameter(yearTo);
            ge.addParameter(country);
            agent.postGuiEvent(ge);
 
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this,
                "enter year and cost.",
                "error", JOptionPane.ERROR_MESSAGE);
        }
    }
 
    private void onBuy() {
        int row = table.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this,
                "select car.",
                "nothing selected", JOptionPane.WARNING_MESSAGE);
            return;
        }
        int modelRow = table.convertRowIndexToModel(row);
        int vin = (Integer) tableModel.getValueAt(modelRow, 0);
 
        setStatus("searching for VIN=" + vin + "...", true);
 
        GuiEvent ge = new GuiEvent(this, Buyer.BUY_EVENT);
        ge.addParameter(vin);
        agent.postGuiEvent(ge);
    }
 
    public void updateCarTable(CarListMsg clm) {
        SwingUtilities.invokeLater(() -> {
            tableModel.setRowCount(0);
 
            jade.util.leap.List cars = clm.getCarListLine().getList();
            if (cars == null || cars.isEmpty()) {
                setStatus("no cars found.", false);
                return;
            }
            for (int i = 0; i < cars.size(); i++) {
                CarData cd = (CarData) cars.get(i);
                tableModel.addRow(new Object[]{
                    cd.getVIN(),
                    cd.getModel().getMaker().getMakeName(),
                    cd.getModel().getModelName(),
                    cd.getModel().getModification(),
                    cd.getColor(),
                    cd.getEngine(),
                    cd.getYearBuilt(),
                    cd.getCarPrice()
                });
            }
            setStatus("Found: " + cars.size() + " cars.", true);
        });
    }
 
    public void showBuyResult(BuyCarResponse r) {
        SwingUtilities.invokeLater(() -> {
            if (r.getIsApproved()) {
                setStatus("Successfully sold VIN=" + r.getVIN()
                          + "  Kaina: " + r.getPrice() + " €", true);
                JOptionPane.showMessageDialog(this,
                    "Successfully sold\nVIN: " + r.getVIN()
                    + "\nCost: " + r.getPrice() + " €",
                    "Success", JOptionPane.INFORMATION_MESSAGE);
                // Pašaliname nupirktą automobilį iš sąrašo
                removeRowByVIN(r.getVIN());
            } else {
                setStatus("Unsuccessfully sold", false);
                JOptionPane.showMessageDialog(this,
                    "unsuccess",
                    "unsuccess", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
 
    public void setStatus(String text, boolean ok) {
        SwingUtilities.invokeLater(() -> {
            lblStatus.setText(text);
            lblStatus.setForeground(ok ? new Color(0, 100, 0) : Color.RED);
        });
    }
 
    private void removeRowByVIN(int vin) {
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            if ((Integer) tableModel.getValueAt(i, 0) == vin) {
                tableModel.removeRow(i);
                break;
            }
        }
    }
 
    private void styleButton(JButton btn, Color bg) {
        btn.setBackground(bg);
        btn.setForeground(Color.WHITE);
        btn.setFocusPainted(false);
        btn.setOpaque(true);
    }
}