/*
Auto-generated by: https://github.com/pmndrs/gltfjsx
*/

import * as THREE from 'three'
import React, { useMemo, useRef, useState } from 'react'
import { useGLTF } from '@react-three/drei/useGLTF'

import { GLTF } from 'three/examples/jsm/loaders/GLTFLoader'
import { Color, FrontSide, MeshLambertMaterial } from 'three'
import useStore from '../../store'

type GLTFResult = GLTF & {
  nodes: {
    computer_mesh: THREE.Mesh
    computer_mesh_1: THREE.Mesh
    computer_mesh_2: THREE.Mesh
  }
  materials: {
    keyboard: THREE.MeshStandardMaterial
    marble: THREE.MeshStandardMaterial
    computer_screen: THREE.MeshStandardMaterial
  }
}

type ComputerProps = {
  obraId: number
}

export default function Model(props: ComputerProps & JSX.IntrinsicElements['group']) {
  const pointerLockControls = useStore((state) => state.pointerLockControls)
  const setModalObra = useStore((state) => state.setModalObra)

  const group = useRef<THREE.Group>()
  const [currentMaterial, setCurrentMaterial] = useState(false)
  const { nodes, materials } = useGLTF('/model/computer.glb') as GLTFResult

  const onMaterial = useMemo(() => {
    const m = new MeshLambertMaterial({
      color: new Color('#57bc78'),
      emissive: new Color('#97ffbd'),
      side: FrontSide,
      flatShading: false,
    })

    return m
  }, [])

  const mat = currentMaterial ? onMaterial : materials.computer_screen

  return (
    <group
      ref={group}
      {...props}
      dispose={null}
      onPointerOver={() => {
        setCurrentMaterial(true)
      }}
      onPointerOut={() => setCurrentMaterial(false)}
      onClick={() => {
        if (pointerLockControls) {
          setModalObra(props.obraId)
          setTimeout(() => {
            pointerLockControls.unlock?.()
          }, 500)
        }
      }}
    >
      <mesh material={materials.keyboard} geometry={nodes.computer_mesh.geometry} />
      <mesh material={materials.marble} geometry={nodes.computer_mesh_1.geometry} />
      <mesh material={mat} geometry={nodes.computer_mesh_2.geometry} />
    </group>
  )
}

useGLTF.preload('/model/computer.glb')
