import { IonContent, ReactComponentOrElement } from '@ionic/react';
import react, {
  ReactComponentElement,
  useEffect,
  useRef,
  useState,
} from 'react';

import './Map.css';
import MouseHandler from './MouseHandler';
import SlippyBoard from './SlippyBoard';
import Tile from './Tile';
import fakeTile from './FakeTile.svg';

interface MapProperties {
  height: number;
  width: number;
}

const Map: react.FC<MapProperties> = (props: MapProperties) => {
  const nbTiles =
    Math.ceil((Math.max(props.width, props.height) * 2) / 256) + 2;
  const boardSize = nbTiles * 256;

  const [shift, setShift] = useState({ x: -boardSize / 2, y: -boardSize / 2 });
  const [zoom, setZoom] = useState(1);

  const addShift = (deltaShift: { x: number; y: number }) => {
    setShift({ x: shift.x + deltaShift.x, y: shift.y + deltaShift.y });
  };

  const addZoom = (zoomFactor: number, center: { x: number; y: number }) => {
    addShift({
      x: (shift.x - center.x) * (zoomFactor - 1),
      y: (shift.y - center.y) * (zoomFactor - 1),
    });
    setZoom(zoom * zoomFactor);
  };

  console.log(`Rendering Map, zoom:${zoom}, shift:${JSON.stringify(shift)}`);

  var initialTiledLayer: any[][] = [];
  for (let row = 0; row < nbTiles; row++) {
    let tileRow = [];
    for (let col = 0; col < nbTiles; col++) {
      tileRow.push(<g key={`${row}/${col}`} />);
    }
    initialTiledLayer.push(tileRow);
  }

  const [tiledLayer, setTiledLayer] = useState(initialTiledLayer);

  useEffect(() => {
    const firstVisibleTiles = {
      x: Math.max(Math.floor(-shift.x / 256 / zoom), 0),
      y: Math.max(Math.floor(-shift.y / 256 / zoom), 0),
    };

    const lastVisibleTiles = {
      x: Math.min(
        Math.ceil(firstVisibleTiles.x + props.width / 256 / zoom),
        nbTiles - 1
      ),
      y: Math.min(
        Math.ceil(firstVisibleTiles.y + props.height / 256 / zoom),
        nbTiles - 1
      ),
    };
    console.log(
      `Adding new tiles if needed for  ${JSON.stringify(
        firstVisibleTiles
      )}/${JSON.stringify(lastVisibleTiles)}.`
    );
    const newTiledLayer: any[][] = [];
    for (let row = 0; row < nbTiles; row++) {
      let tileRow = [];
      for (let col = 0; col < nbTiles; col++) {
        const key = `${row}/${col}`;
        if (
          tiledLayer[row][col].type === 'g' &&
          row >= firstVisibleTiles.y &&
          row <= lastVisibleTiles.y &&
          col >= firstVisibleTiles.x &&
          col <= lastVisibleTiles.x
        ) {
          console.log(`Adding tile ${row}/${col}`);
          tileRow.push(
            <Tile
              key={key}
              href={fakeTile}
              x={col * 256}
              y={row * 256}
              delay={1000}
            />
          );
        } else {
          //          tileRow.push(<g key={key} />);
          tileRow.push(tiledLayer[row][col]);
        }
      }
      newTiledLayer.push(tileRow);
    }

    setTiledLayer(newTiledLayer);
  }, [shift, zoom, nbTiles]);

  //  console.log(`tiledLayer: ${JSON.stringify(tiledLayer)}`);

  return (
    <IonContent fullscreen={true}>
      <div
        className='map'
        style={{ width: props.width + 'px', height: props.height + 'px' }}
      >
        <MouseHandler
          shift={shift}
          addShift={addShift}
          zoom={zoom}
          addZoom={addZoom}
          boardSize={boardSize}
        />
        <SlippyBoard
          boardSize={boardSize}
          shift={shift}
          zoom={zoom}
          layers={[
            {
              key: 'background',
              content: (
                <rect
                  x='0'
                  y='0'
                  width={boardSize}
                  height={boardSize}
                  fill='red'
                />
              ),
            },
            { key: 'tiles', content: tiledLayer },
            { key: 'circle', content: <circle cx='50' cy='50' r='50' /> },
          ]}
        />
      </div>
    </IonContent>
  );
};

export default Map;
