"use client";

import { Mesh } from "three";
import { useEffect, useRef } from "react";
import { Canvas, useLoader, useFrame } from "@react-three/fiber";
import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import styles from "./skeleton.module.css";
import { appendFile } from "fs";
import {
  MaterialReferenceNode,
  positionGeometry,
} from "three/examples/jsm/nodes/Nodes.js";
import { OrbitControls, useScroll } from "@react-three/drei";

function SkeletonMesh() {
  const mesh = useRef<Mesh>(null!);
  let head = useLoader(GLTFLoader, "/models/skeleton/head.gltf");
  const eye = useLoader(GLTFLoader, "/models/skeleton/eye.gltf");
  const eye2 = useLoader(GLTFLoader, "/models/skeleton/eye.gltf");
  const body = useLoader(GLTFLoader, "/models/skeleton/body.gltf");
  return (
    <group>
      <mesh
        ref={mesh}
        scale={0.1}
        position={[-1, 0.72, -0.91]}
        rotation={[
          THREE.MathUtils.degToRad(0),
          THREE.MathUtils.degToRad(70),
          THREE.MathUtils.degToRad(0),
        ]}
      >
        <primitive object={eye.scene} />
      </mesh>
      <mesh
        ref={mesh}
        scale={0.1}
        position={[-2.3, 0.5, -1]}
        rotation={[
          THREE.MathUtils.degToRad(0),
          THREE.MathUtils.degToRad(25),
          THREE.MathUtils.degToRad(0),
        ]}
      >
        <primitive object={head.scene} />
      </mesh>
      <mesh
        ref={mesh}
        scale={0.1}
        position={[-2.03, 0.72, -0.91]}
        rotation={[
          THREE.MathUtils.degToRad(0),
          THREE.MathUtils.degToRad(70),
          THREE.MathUtils.degToRad(0),
        ]}
      >
        <primitive object={eye.scene} />
      </mesh>
    </group>
  );
}

export default function Skeleton() {
  let cameraPosition = 0;
  const meshArray: Array<{ x: number; y: number; z: number }> = [];
  const starNumber = Math.floor(Math.random() * 300) + 200;
  for (var i = 0; i < starNumber; i++) {
    meshArray.push({
      x: Math.random() * (-50 + 100) - 100,
      y: Math.random() * (50 + 50) - 50,
      z: Math.random() * (100 + 100) - 100,
    });
  }

  return (
    <Canvas
      onScroll={(el) => {
        cameraPosition += 1;
      }}
      className={styles.Canvas}
      camera={{
        position: [0, 1.2, cameraPosition],
        rotation: [0, THREE.MathUtils.degToRad(90), 0],
      }}
    >
      {/* <OrbitControls /> */}
      <pointLight intensity={4} />
      <gridHelper args={[99, 99, "grey", "grey"]} />
      <SkeletonMesh />
      <group>
        <ambientLight />
        {meshArray.map((el) => {
          return (
            <mesh position={[el.x, el.y, el.z]}>
              <sphereGeometry args={[0.2 * Math.random()]} />
              <meshPhysicalMaterial color="white" />
            </mesh>
          );
        })}
      </group>
    </Canvas>
  );
}
