import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO Klassenbeschreibung
 */
public class BoardDisplay extends JPanel {
    private JButton[][] fields;
    private int gridSize;
    private List <Ship> ships;
    private Ship currentShip;
    private Player player;
    private boolean vertical = false;

    /**
     * Konstruktor der startLocalGame.
     * TODO fertig schreiben
     * @param gridSize
     * @param player
     */
    public BoardDisplay(int gridSize, Player player) {
        super(new GridLayout(gridSize + 1, gridSize + 1)); // +1 wegen extra Zeile/Spalte
        this.fields = new JButton[gridSize][gridSize];
        this.ships = new ArrayList<>();
        this.player = player;
        this.gridSize = gridSize;
        System.out.println("Name in Boarddisplay: " + player.getName());//Testausgabe
        // Erstellung von Spielfeld
        for (int i = 0; i <= gridSize; i++) {
            for (int j = 0; j <= gridSize; j++) {
                final int x = i - 1; // Temporäre Variable
                final int y = j - 1; // Temporäre Variable
                if (i == 0 && j == 0) {
                    add(new JLabel(" "));
                } else if (i == 0) {
                    JLabel colLabel = new JLabel(String.valueOf(j));
                    colLabel.setHorizontalAlignment(SwingConstants.CENTER);
                    colLabel.setFont(new Font("Arial", Font.BOLD, 14));
                    add(colLabel);
                } else if (j == 0) {
                    JLabel rowLabel = new JLabel(String.valueOf((char) ('A' + i - 1)));
                    rowLabel.setHorizontalAlignment(SwingConstants.CENTER);
                    rowLabel.setFont(new Font("Arial", Font.BOLD, 14));
                    add(rowLabel);
                } else {
                    // Spielfeld (interaktive Zellen)
                    JButton field = new JButton("");
                    field.setBackground(Color.BLUE);
                    field.setOpaque(true);
                    field.setBorderPainted(true);
                    fields[i - 1][j - 1] = field;
                    add(field);
                    //field.addMouseListener(new MouseAdapter() {
                       // @Override
                        //public void mouseClicked(MouseEvent e) {
                         //   if (SwingUtilities.isRightMouseButton(e)) {
                         //       handleFieldClick(field);
                         //   }
                       // }

                        //@Override
                        //public void mouseExited(MouseEvent e) {
                            // field.setBackground(Color.LIGHT_GRAY);
                       // }
                   // });
                    field.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            if (SwingUtilities.isRightMouseButton(e)) {
                                togglePlacementDirection(); // Ausrichtung ändern
                            } else if (SwingUtilities.isLeftMouseButton(e)) {
                                Point o = new Point(x, y);
                                currentShip.setHorizontal(vertical);
                                handleFieldClick(o); // Linksklick -> Schiff platzieren
                                vertical = false; // TODO nur nach auswahl von neuem Modul wieder auf false setzten
                            }
                        }
                    });
                }
            }
        }
       // this.ships = new ArrayList<Ship>();
    }



    public void selectCurrentShip(Ship ship) {
        this.currentShip = ship;
    }

    public void resetAllShips() {
        ships.clear();
        this.currentShip = null;
        for(int i = 0; i < gridSize; i++) {
            for(int j = 0; j < gridSize; j++) {
                fields[i][j].setBackground(Color.BLUE);
            }
        }
    }
    /**
     * TODO Funktion beschreiben etc.
     * @param ship
     * @param o
     * @param horizontal
     * @param player
     * @return
     */
    private boolean setShip(Ship ship, Point o, boolean horizontal,Player player) {
        //boolean a = true;
        if (placeable(ship, ship.getPosition(), horizontal)) {
            ship.setPosition(new Point(o.getX(),o.getY()),player.getBoard().getShips(),gridSize);
            ship.setHorizontal(horizontal);
            ships.add(ship);
            List<Point> occupied = ship.getOccupiedPoints();
            for(Point p: occupied) {
                fields[p.getX()][p.getY()].setBackground(Color.LIGHT_GRAY);
            }
            return true;
        }else{
            return false;
        }
    }

    /*private boolean placeable(Ship ship,Point o, boolean horizontal) {
        if (horizontal && (o.getX() + ship.getSize() > gridSize)) { // Fehler
            return false;
        }
        if (!horizontal && (o.getY() + ship.getSize() > gridSize)) {
            return false;
        }
        return true;
    }*/

    /**
     * TODO Funktion beschreiben etc.
     * @param ship
     * @param o
     * @param horizontal
     * @return
     */
    private boolean placeable(Ship ship, Point o, boolean horizontal) {
        if (horizontal && (o.getX() + ship.getSize() > gridSize)) {
            return false;
        }
        if (!horizontal && (o.getY() + ship.getSize() > gridSize)) {
            return false;
        }

        // Prüfen auf Kollision mit bestehenden Schiffen
        for (Ship other : ships) {
            for (Point p : other.getOccupiedPoints()) {
                for (Point newP : ship.getOccupiedPoints()) {
                    if (p.equals(newP)) {
                        return false; // Überschneidung gefunden
                    }
                }
            }
        }

        return true;
    }

    /**
     * Wechselt die Platzierungsrichtung zwischen horizontal und vertikal.
     */
    private void togglePlacementDirection() {
        vertical = !vertical;
        String direction = vertical ? "vertikal" : "horizontal";
        System.out.println("Platzierungsrichtung geändert zu: " + direction);
    }

    /**
     * Handhabt das Platzieren eines Schiffs auf dem Spielfeld.
     * @param o Die Koordinaten des Klicks.
     */
    private void handleFieldClick(Point o) {
        if (!this.currentShip.setPosition(o,player.getBoard().getShips(),this.gridSize)) {
        }
        paintFields();
       //if(this.currentShip.isPlaced()){
         //  this.currentShip.
      // };
        // Beispiel: Setze ein Schiff bei einem Klick
        //if (setShip(new Ship(3, "TestShip"), o, true,player)) {
         //   field.setBackground(Color.BLUE); // Visualisiere Schiff
        //}
    }


    public void paintFields() {
        for(int i = 0; i < gridSize; i++) {
            for(int j = 0; j < gridSize; j++) {
                if(fields[i][j] == null) {
                    continue;
                }
                fields[i][j].setBackground(Color.BLUE);
                for(Ship ship: player.getBoard().getShips()) {
                    if(ship.isShipOnPos(new Point(i,j))) {
                        fields[i][j].setBackground(Color.LIGHT_GRAY);
                        break;
                    }
                }
            }
        }
    }
}