import * as THREE from 'three'
import { Points, useGLTF, OrbitControls } from '@react-three/drei'
import { GLTF } from 'three-stdlib'
import { useFrame, Canvas, useThree } from '@react-three/fiber'
import { useMemo, useRef, Suspense, useState, useEffect } from 'react'
import { EffectComposer, SelectiveBloom } from '@react-three/postprocessing'
import { useLoader } from '@react-three/fiber'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { CubeTextureLoader } from 'three'
import { SphereGeometry } from 'three';
import { VRMLoaderPlugin, VRM, VRMUtils, VRMSpringBoneLoaderPlugin } from "@pixiv/three-vrm";

interface ModelPropsVrm {
  url: string
  position?: [number, number, number]
  scale?: number 
}

const Vrm: React.FC<ModelPropsVrm> = ({ url, position = [0, 0, 0], scale  = 1}) => {

	const gltf = useLoader(GLTFLoader, url, (loader) => {
		loader.register((parser) => new VRMLoaderPlugin(parser));
		loader.register((parser) => new VRMSpringBoneLoaderPlugin(parser));
	});
	const [vrm, setVrm] = useState<VRM | null>(null);
	useEffect(() => {
		if (gltf) {
			const vrmModel = gltf.userData.vrm as VRM;
			VRMUtils.removeUnnecessaryJoints(vrmModel.scene);
			setVrm(vrmModel);
			if (vrmModel) {
				//vrmModel.scene.rotation.y = Math.PI;
				vrmModel.scene.rotation.y = 0;
				vrmModel.scene.rotation.x = 5;
				vrmModel.scene.rotation.z = 0;
				vrmModel.scene.position.set(...position);
				vrmModel.scene.scale.setScalar(scale);
			}

		}
	}, [gltf, position, scale]);
	useFrame((state, delta) => {
		if (vrm) {
			vrm.update(delta);
		}
	});

	return gltf ? <primitive object={gltf.scene} /> : null;
};

export default Vrm;

type GLTFResult = GLTF & {
  nodes: {
    Object_2: THREE.Mesh
  }
  materials: {
    ['Scene_-_Root']: THREE.PointsMaterial
  }
}

export function Galaxy(props: JSX.IntrinsicElements['group']) {
	const ref = useRef<THREE.Group>(null!)
	const galaxyCenterLightRef = useRef<THREE.PointLight>(null!)
	const searchParams = new URLSearchParams(window.location.search);
	var g = searchParams.get('g') ?? 'galaxy';
	var model_path_default = "./models/galaxy.glb"
	var model_path = "./models/" + g + ".glb"
	var model_scale = 0.05;

	const { nodes } = useGLTF(model_path_default) as GLTFResult
	const [positions, colors] = useMemo(() => {
			nodes.Object_2.geometry.center()
    const positions = new Float32Array(
      nodes.Object_2.geometry.attributes.position.array.buffer
    )
    const colors = new Float32Array(positions.length)
    const getDistanceToCenter = (x: number, y: number, z: number) =>
      Math.sqrt(x * x + y * y + z * z)
		var model_color = 100;
		if (g === 'sun'){
			const sphereGeometry = new SphereGeometry(1, 332, 332);
			nodes.Object_2.geometry = sphereGeometry;
			model_scale = 1;
		} else if (g === 'moon'){
			const sphereGeometry = new SphereGeometry(1, 132, 132);
			nodes.Object_2.geometry = sphereGeometry;
			model_color = 1;
			model_scale = 0.1;
		} else if (g === 'earth'){
			const sphereGeometry = new SphereGeometry(1, 232, 232);
			nodes.Object_2.geometry = sphereGeometry;
			model_color = 0.5;
			model_scale = 0.3;
		} else if (g === 'asteroid') {
			const sphereGeometry = new SphereGeometry(1, 32, 32);
			nodes.Object_2.geometry = sphereGeometry;
			model_color = 1;
			model_scale = 0.1;
		} else if (g === 'neutron') {
			model_color = 1;
		}
			// make colors closer to 0,0,0 be more reddish and colors further away be more blueish
			const color = new THREE.Color()
			for (let i = 0; i < positions.length; i += 3) {
				const x = positions[i]
				const y = positions[i + 1]
				const z = positions[i + 2]
				const distanceToCenter = getDistanceToCenter(x, y, z)
				const normalizedDistanceToCenter = distanceToCenter / model_color
				// make colors closer to 0,0,0 be more reddish and colors further away be more blueish (do not use hsl)
				color.setHSL(
					(0.15 * (0.21 + Math.cos(distanceToCenter * 0.02))) / 2,
					0.75,
					0.6
				)
				color.setRGB(
					Math.cos(normalizedDistanceToCenter),
					THREE.MathUtils.randFloat(0, 0.8),
					Math.sin(normalizedDistanceToCenter)
				)
				color.toArray(colors, i)
			}

    return [positions, colors]
  }, [nodes])

  // slowly rotate the galaxy
  
  useFrame(({ clock }) => {
    // zoom in and out
    ref.current.rotation.z = clock.getElapsedTime() / 2
			 ref.current.scale.setScalar(Math.sin(clock.getElapsedTime() / 10) + 1.2)
  })

	//  make particles glow
	// <VRMModel url="./models/ai.vrm" vrmaurl="./models/fly_a.vrma" />

	var m = searchParams.get('m') ?? 't';
	 model_path = "./models/" + m + ".vrm";

  return (
   <group {...props} dispose={null} ref={ref}>
			<Vrm url={model_path} position={[2, -4, 8]} scale={10} />
			<pointLight
        position={[0, 0, 0]}
        ref={galaxyCenterLightRef}
        intensity={0.5}
      />
      <Points scale={model_scale} positions={positions} colors={colors}>
        <pointsMaterial
          //map={starTexture}
          transparent
          depthWrite={false}
          vertexColors
          opacity={0.4}
          depthTest
          size={0.01}
        />
      </Points>
      <EffectComposer autoClear={false}>
        <SelectiveBloom
          intensity={5}
          luminanceThreshold={0.01}
          luminanceSmoothing={0.225}
          lights={[galaxyCenterLightRef]}
        />
      </EffectComposer>
		    <ambientLight intensity={1} />
			</group>
  )
}

export const ThreeFiberGalaxy = () => {
	return (
		<Canvas camera={{ position: [0, 12, 0], fov: 75 }}
		shadows
		gl={{
			//toneMapping: THREE.ACESFilmicToneMapping,
			//toneMapping: THREE.ReinhardToneMapping,
			toneMapping: THREE.NeutralToneMapping,
				toneMappingExposure: 1.5,
				alpha: true,
				powerPreference: "high-performance",
				antialias: true,
				//stencil: false,
				//depth: false
		}}
		>
		<ambientLight intensity={1} />
		<pointLight position={[10, 10, 10]} />
		<directionalLight 
		color="white" 
		castShadow 
		position={[0, 10, 0]} 
		intensity={1.5} 
		shadow-mapSize={[1024, 1024]}/>
		<OrbitControls
		//minAzimuthAngle={-Math.PI / 4}
			//maxAzimuthAngle={Math.PI / 4}
			//minPolarAngle={Math.PI / 1}
			maxPolarAngle={Math.PI - Math.PI / 1}
			minDistance={20} maxDistance={30}
			enableZoom={true} enablePan={false} enableRotate={true}
			zoomSpeed={0.5}
			panSpeed={0.5}
			rotateSpeed={0.5} />	
		<pointLight position={[10, 10, 10]} />
		<Suspense fallback={null}>
		<Galaxy position={[0, 9, 0]} />
		</Suspense>
		</Canvas>
	)
}

useGLTF.preload('./models/galaxy.glb')


