import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

public class InventoryManagerApp extends JFrame {
    private final DefaultTableModel model = new DefaultTableModel(
            new Object[]{"Nama", "Asset Tag", "Lokasi", "Pemakai", "Status"}, 0);
    private final JTable table = new JTable(model);
    private final JTextField txtName = new JTextField();
    private final JTextField txtTag = new JTextField();
    private final JTextField txtLocation = new JTextField();
    private final JTextField txtUser = new JTextField();
    private final JComboBox<String> cmbStatus = new JComboBox<>(new String[]{"Ready", "In Use", "Repair", "Retired"});
    private final JTextField txtFilter = new JTextField();
    private final Path dataFile = Paths.get("data", "inventory.csv");

    public InventoryManagerApp() {
        setTitle("Inventory Manager Java");
        setSize(980, 640);
        setMinimumSize(new Dimension(900, 560));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel root = new JPanel(new BorderLayout(10, 10));
        root.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));

        JLabel header = new JLabel("Inventory Manager Java");
        header.setFont(new Font("Segoe UI", Font.BOLD, 24));
        root.add(header, BorderLayout.NORTH);

        JPanel form = new JPanel(new GridLayout(3, 5, 8, 8));
        form.add(new JLabel("Nama"));
        form.add(new JLabel("Asset Tag"));
        form.add(new JLabel("Lokasi"));
        form.add(new JLabel("Pemakai"));
        form.add(new JLabel("Status"));
        form.add(txtName);
        form.add(txtTag);
        form.add(txtLocation);
        form.add(txtUser);
        form.add(cmbStatus);

        JButton btnAdd = new JButton("Tambah");
        JButton btnUpdate = new JButton("Update");
        JButton btnDelete = new JButton("Hapus");
        JButton btnSave = new JButton("Simpan CSV");
        JButton btnLoad = new JButton("Load CSV");
        form.add(btnAdd);
        form.add(btnUpdate);
        form.add(btnDelete);
        form.add(btnSave);
        form.add(btnLoad);

        root.add(form, BorderLayout.CENTER);

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(900, 330));
        root.add(scrollPane, BorderLayout.SOUTH);

        JPanel footer = new JPanel(new BorderLayout(8, 8));
        footer.add(new JLabel("Filter cepat"), BorderLayout.WEST);
        footer.add(txtFilter, BorderLayout.CENTER);
        JButton btnFilter = new JButton("Cari");
        JButton btnSeed = new JButton("Seed Demo");
        JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        right.add(btnSeed);
        right.add(btnFilter);
        footer.add(right, BorderLayout.EAST);

        JPanel container = new JPanel(new BorderLayout(10, 10));
        container.add(root, BorderLayout.CENTER);
        container.add(footer, BorderLayout.SOUTH);

        setContentPane(container);

        btnAdd.addActionListener(e -> addItem());
        btnUpdate.addActionListener(e -> updateItem());
        btnDelete.addActionListener(e -> deleteItem());
        btnSave.addActionListener(e -> saveCsv());
        btnLoad.addActionListener(e -> loadCsv());
        btnFilter.addActionListener(e -> filterRows());
        btnSeed.addActionListener(e -> seedDemo());
        table.getSelectionModel().addListSelectionListener(e -> fillFormFromSelection());

        seedIfEmpty();
    }

    private void addItem() {
        if (txtName.getText().trim().isEmpty() || txtTag.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Nama dan Asset Tag wajib diisi.");
            return;
        }
        model.addRow(new Object[]{
                txtName.getText().trim(),
                txtTag.getText().trim(),
                txtLocation.getText().trim(),
                txtUser.getText().trim(),
                cmbStatus.getSelectedItem()
        });
        clearForm();
    }

    private void updateItem() {
        int row = table.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this, "Pilih baris yang ingin diupdate.");
            return;
        }
        model.setValueAt(txtName.getText().trim(), row, 0);
        model.setValueAt(txtTag.getText().trim(), row, 1);
        model.setValueAt(txtLocation.getText().trim(), row, 2);
        model.setValueAt(txtUser.getText().trim(), row, 3);
        model.setValueAt(cmbStatus.getSelectedItem(), row, 4);
    }

    private void deleteItem() {
        int row = table.getSelectedRow();
        if (row >= 0) {
            model.removeRow(row);
            clearForm();
        }
    }

    private void clearForm() {
        txtName.setText("");
        txtTag.setText("");
        txtLocation.setText("");
        txtUser.setText("");
        cmbStatus.setSelectedIndex(0);
    }

    private void fillFormFromSelection() {
        int row = table.getSelectedRow();
        if (row < 0) return;
        txtName.setText(String.valueOf(model.getValueAt(row, 0)));
        txtTag.setText(String.valueOf(model.getValueAt(row, 1)));
        txtLocation.setText(String.valueOf(model.getValueAt(row, 2)));
        txtUser.setText(String.valueOf(model.getValueAt(row, 3)));
        cmbStatus.setSelectedItem(String.valueOf(model.getValueAt(row, 4)));
    }

    private void saveCsv() {
        try {
            Files.createDirectories(dataFile.getParent());
            try (BufferedWriter writer = Files.newBufferedWriter(dataFile)) {
                for (int i = 0; i < model.getRowCount(); i++) {
                    List<String> parts = new ArrayList<>();
                    for (int j = 0; j < model.getColumnCount(); j++) {
                        parts.add(String.valueOf(model.getValueAt(i, j)).replace(",", " "));
                    }
                    writer.write(String.join(",", parts));
                    writer.newLine();
                }
            }
            JOptionPane.showMessageDialog(this, "Data disimpan ke " + dataFile.toAbsolutePath());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Gagal simpan: " + ex.getMessage());
        }
    }

    private void loadCsv() {
        model.setRowCount(0);
        if (!Files.exists(dataFile)) {
            JOptionPane.showMessageDialog(this, "File CSV belum ada.");
            return;
        }
        try (BufferedReader reader = Files.newBufferedReader(dataFile)) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] p = line.split(",", -1);
                if (p.length >= 5) {
                    model.addRow(new Object[]{p[0], p[1], p[2], p[3], p[4]});
                }
            }
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Gagal load: " + ex.getMessage());
        }
    }

    private void filterRows() {
        String key = txtFilter.getText().trim().toLowerCase();
        if (key.isEmpty()) {
            return;
        }
        for (int i = 0; i < model.getRowCount(); i++) {
            String merged = (
                    model.getValueAt(i, 0) + " " +
                    model.getValueAt(i, 1) + " " +
                    model.getValueAt(i, 2) + " " +
                    model.getValueAt(i, 3) + " " +
                    model.getValueAt(i, 4)
            ).toLowerCase();
            if (merged.contains(key)) {
                table.setRowSelectionInterval(i, i);
                table.scrollRectToVisible(table.getCellRect(i, 0, true));
                return;
            }
        }
        JOptionPane.showMessageDialog(this, "Data tidak ditemukan.");
    }

    private void seedDemo() {
        model.setRowCount(0);
        model.addRow(new Object[]{"Laptop Admin", "LT-001", "Jakarta", "Rina", "In Use"});
        model.addRow(new Object[]{"Access Point", "NW-220", "Ruang Server", "Tim IT", "Ready"});
        model.addRow(new Object[]{"Printer Kasir", "PR-812", "Cabang A", "Doni", "Repair"});
        model.addRow(new Object[]{"Scanner Gudang", "SC-115", "Gudang", "Lina", "Ready"});
    }

    private void seedIfEmpty() {
        if (model.getRowCount() == 0) {
            seedDemo();
        }
    }

    public static void main(String[] args) {
        if (args.length > 0 && "--smoke-test".equals(args[0])) {
            System.out.println("{\"app\":\"inventory-manager-java\",\"status\":\"compile-ready\"}");
            return;
        }
        SwingUtilities.invokeLater(() -> new InventoryManagerApp().setVisible(true));
    }
}
