package thb.jeanluc.adventure.io;

import thb.jeanluc.adventure.io.text.CellState;
import thb.jeanluc.adventure.io.text.Connection;
import thb.jeanluc.adventure.io.text.MapView;
import thb.jeanluc.adventure.io.text.RoomCell;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.List;

/**
 * Draws a {@link MapView} as outlined rooms linked by corridors (Graphics2D).
 *
 * <p>The map is scaled to <em>fit</em> the side panel, so it never needs
 * scrollbars at normal zoom and re-fits whenever the window (and thus the
 * panel) is resized. The {@link #setZoom(float) zoom} from {@code Ctrl +/-}
 * multiplies on top of the fit scale (zoom &gt; 1 enlarges and may scroll).</p>
 */
public class MapPanel extends JComponent {

    private static final int BASE_CELL_W = 96;
    private static final int BASE_CELL_H = 46;
    private static final int BASE_GAP_X = 34;
    private static final int BASE_GAP_Y = 30;
    private static final int BASE_PAD = 16;
    private static final float BASE_FONT = 11f;

    private static final Color BG = new Color(0x0e, 0x12, 0x18);
    private static final Color CORRIDOR = new Color(0x46, 0x70, 0x8a);
    private static final Color VISITED = new Color(0xcf, 0xd6, 0xe0);
    private static final Color CURRENT = new Color(0xe6, 0xc3, 0x4a);
    private static final Color KNOWN = new Color(0x3a, 0x46, 0x55);

    private final Font baseFont;
    private float zoom = 1f;
    private MapView view = new MapView(List.of(), List.of());

    public MapPanel(Font font) {
        this.baseFont = font;
        setBackground(BG);
        setOpaque(true);
    }

    /** Sets the user zoom multiplier (applied on top of the fit-to-panel scale). */
    public void setZoom(float zoom) {
        SwingUtilities.invokeLater(() -> {
            this.zoom = Math.max(0.4f, zoom);
            revalidate();
            repaint();
        });
    }

    /** Replaces the rendered map. */
    public void show(MapView v) {
        SwingUtilities.invokeLater(() -> {
            this.view = v;
            revalidate();
            repaint();
        });
    }

    /** The space the map should fit into: the enclosing scroll pane's viewport area. */
    private Dimension available() {
        Container p = getParent();
        if (p instanceof JViewport && p.getParent() instanceof JScrollPane sp) {
            Insets in = sp.getInsets();
            int w = sp.getWidth() - in.left - in.right;
            int h = sp.getHeight() - in.top - in.bottom;
            if (w > 0 && h > 0) {
                return new Dimension(w, h);
            }
        }
        Dimension s = getSize();
        return (s.width > 0 && s.height > 0) ? s : new Dimension(220, 320);
    }

    private int[] gridBounds() {
        int maxX = 0;
        int maxY = 0;
        for (RoomCell c : view.cells()) {
            maxX = Math.max(maxX, c.x());
            maxY = Math.max(maxY, c.y());
        }
        return new int[]{maxX, maxY};
    }

    /** Fit-to-panel scale times the user zoom. */
    private float effScale(Dimension avail, int[] b) {
        double natW = 2.0 * BASE_PAD + (b[0] + 1) * BASE_CELL_W + b[0] * BASE_GAP_X;
        double natH = 2.0 * BASE_PAD + (b[1] + 1) * BASE_CELL_H + b[1] * BASE_GAP_Y;
        if (natW <= 0 || natH <= 0) {
            return zoom;
        }
        double fit = Math.min(avail.width / natW, avail.height / natH);
        fit = Math.max(0.3, Math.min(3.0, fit));
        return (float) (fit * zoom);
    }

    private Dimension content(float eff, int[] b) {
        int pad = Math.round(BASE_PAD * eff);
        int cw = Math.round(BASE_CELL_W * eff);
        int ch = Math.round(BASE_CELL_H * eff);
        int gx = Math.round(BASE_GAP_X * eff);
        int gy = Math.round(BASE_GAP_Y * eff);
        return new Dimension(pad * 2 + (b[0] + 1) * cw + b[0] * gx,
                pad * 2 + (b[1] + 1) * ch + b[1] * gy);
    }

    @Override
    public Dimension getPreferredSize() {
        if (view.cells().isEmpty()) {
            return available();
        }
        Dimension avail = available();
        int[] b = gridBounds();
        Dimension c = content(effScale(avail, b), b);
        // Fill the viewport when the map is smaller; allow growth (scroll) when zoomed in.
        return new Dimension(Math.max(c.width, avail.width), Math.max(c.height, avail.height));
    }

    @Override
    protected void paintComponent(Graphics g0) {
        Graphics2D g = (Graphics2D) g0.create();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(BG);
        g.fillRect(0, 0, getWidth(), getHeight());
        if (view.cells().isEmpty()) {
            g.dispose();
            return;
        }

        int[] b = gridBounds();
        float eff = effScale(available(), b);
        g.setFont(baseFont.deriveFont(BASE_FONT * eff));

        int cellW = Math.round(BASE_CELL_W * eff);
        int cellH = Math.round(BASE_CELL_H * eff);
        int gapX = Math.round(BASE_GAP_X * eff);
        int gapY = Math.round(BASE_GAP_Y * eff);
        int pad = Math.round(BASE_PAD * eff);
        int arc = Math.round(12 * eff);

        Dimension c = content(eff, b);
        int offX = Math.max(0, (getWidth() - c.width) / 2);
        int offY = Math.max(0, (getHeight() - c.height) / 2);

        Stroke solid = new BasicStroke(2f * eff);
        Stroke dashed = new BasicStroke(1.5f * eff, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                10f, new float[]{4f * eff, 3f * eff}, 0f);

        // corridors first
        for (Connection cn : view.connections()) {
            boolean known = cn.from().state() == CellState.KNOWN || cn.to().state() == CellState.KNOWN;
            g.setStroke(known ? dashed : solid);
            g.setColor(known ? KNOWN : CORRIDOR);
            int x1 = offX + pad + cn.from().x() * (cellW + gapX) + cellW / 2;
            int y1 = offY + pad + cn.from().y() * (cellH + gapY) + cellH / 2;
            int x2 = offX + pad + cn.to().x() * (cellW + gapX) + cellW / 2;
            int y2 = offY + pad + cn.to().y() * (cellH + gapY) + cellH / 2;
            g.drawLine(x1, y1, x2, y2);
        }

        // rooms on top
        for (RoomCell cell : view.cells()) {
            int x = offX + pad + cell.x() * (cellW + gapX);
            int y = offY + pad + cell.y() * (cellH + gapY);
            Color stroke = switch (cell.state()) {
                case CURRENT -> CURRENT;
                case VISITED -> VISITED;
                case KNOWN -> KNOWN;
            };
            g.setColor(cell.state() == CellState.CURRENT
                    ? new Color(0x27, 0x21, 0x10)
                    : new Color(0x11, 0x16, 0x1f));
            g.fillRoundRect(x, y, cellW, cellH, arc, arc);

            g.setStroke(cell.state() == CellState.KNOWN
                    ? dashed
                    : new BasicStroke((cell.state() == CellState.CURRENT ? 2.5f : 1.5f) * eff));
            g.setColor(stroke);
            g.drawRoundRect(x, y, cellW, cellH, arc, arc);

            String label = cell.state() == CellState.KNOWN ? "?" : cell.name();
            int tw = g.getFontMetrics().stringWidth(label);
            int ascent = g.getFontMetrics().getAscent();
            g.setColor(cell.state() == CellState.KNOWN ? KNOWN.brighter() : stroke);
            g.drawString(label, x + (cellW - tw) / 2, y + (cellH + ascent) / 2 - 2);
        }
        g.dispose();
    }
}
