import * as THREE from 'three'
import React, { useEffect, useRef, useState } from 'react'
import Star from './Star'
import { Html, Line } from '@react-three/drei'
import { Vector3 } from 'three'
import useStore from '@/lib/store'
import { useFrame } from '@react-three/fiber'

const Constellation =({data}:any) => {

  const [points, setPoints] = useState<Vector3[]>([])
  const [offset, setOffset] = useState<Vector3>(new Vector3(0, 0, 0))
  const [flag, setFlag] = useState(false)
  const choose = useStore(s => s.choose)
  const lineRef = useRef<any>(null)

  useEffect(()=>{
    const temp = []
    for (let i = 0; i<5 ; i++){
      while(1){
        const pos = new THREE.Vector3(Math.random() *10 -5, Math.random() *10 -5, Math.random() *10 -5)
        let j
        for (j = 0; j<temp.length; j++){
          if(pos.distanceTo(temp[j])<4)
            break
        }
        if(j === temp.length){
          temp.push(pos)
          break
        }
      }
    }  
    temp.push(temp[0])
    setPoints(temp)
    setOffset(new Vector3(Math.random() *40-20, Math.random() *40-20, Math.random() *40-20))
  },[])

  useEffect(()=>{
    if(choose && data){
      setFlag(false)
      data?.stars.map((item:any)=>{
        if(item?.transaction_signature === choose.transaction_signature){
          setFlag(true)
        }
      })
    }else{
      setFlag(false)
    }
  },[choose, data])

  useFrame(({clock })=>{
    if(lineRef.current){
      const time = clock.getElapsedTime();
      const v = flag?(Math.sin(time*2) * 0.25 + 0.7):(Math.sin(time * 2+offset.x+offset.y) * 0.1 + 0.1); // Range: 0 to 1
      lineRef.current.material.color.setRGB(v, v, v)
    }
  })

  return (
    <group position={data?.position?data.position:[0, 0, 0]} name={data?.name}>
      <group position={offset} >
        {
          data?.name &&
          <Html
            wrapperClass = "scene-label"
            zIndexRange={[1, 0]}
            center
          >
            <h1 className={flag?"active":""}>{data.name}</h1>
          </Html>
        }
        {
          data?.stars && points.length>0 &&
          <>
            {
              data.stars.map((item: any, index: number)=><Star key={index} data = {item} pos = {points[index]}/>)
            }
          </>
        }
        {
          points.length>0 &&
          <Line
            points={points}
            lineWidth={1} // Line width
            // color={flag?0xffffff:0x505050}
            ref={lineRef}
          />
        }
      </group>
    </group>
  )
}

export default Constellation