import React, { useCallback, useMemo } from 'react';
import { Plane } from '@react-three/drei';
import { Vector3 } from 'three';
import { MAP_SCALE } from '@map/const/map';
import type { MapRegion } from '@game/struct/region';
import { observer } from 'mobx-react-lite';
import { server } from '@game/network/server';

interface Props {
  item: MapRegion;
}

export const WorldItem = observer((props: Props) => {
  const { item } = props;

  const position = useMemo(() => {
    return new Vector3(item.x, item.y, 0);
  }, [item.x, item.y]);

  const color = useMemo(() => {
    return item.isSelected
      ? 'fde910'
      : (Math.floor(item.itemId * 10 * 0xddf0cf) % 0xffffff || 0xffffff).toString(16).padStart(6, '0');
  }, [item.isSelected, item.itemId]);

  const onClick = useCallback(() => {
    // item.toggle();

    server.selectRegion(item.x, item.y);

    console.log(item);
  }, [item]);

  return (
    <Plane args={[MAP_SCALE, MAP_SCALE]} receiveShadow position={position} onClick={onClick}>
      <meshPhongMaterial color={`#${color}`} />
    </Plane>
  );
});
