import * as THREE from 'three'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import useStore from '@/lib/store'
import { useCursor } from '@react-three/drei'
import { useFrame } from '@react-three/fiber'

const Star = ({data, pos}:any) => {  
  const [color, setColor] = useState(0x111111)
  const [offset] = useState(Math.random()*2*Math.PI)
  useEffect(()=>{
    const colors = [0xf9c54b, 0xa891fb, 0xff9933, 0x00ccff, 0xccb0e9]
    // const colors = [0x009999, 0x3333ff, 0x990099, 0x990000, 0x999966, 0x9900ff, 0x996633, 0x8A2BE2, 0x32CD32, 0x228B22 ]
    setColor(colors[Math.floor(Math.random() * 4.5)])
  },[])

  const r = useMemo(()=>{
    if(data?.amount){
      const rr = Math.cbrt( data.amount * 0.239 ) / 5000
      return (rr>2.5)?2.5:(rr<0.2)?0.2:rr
    }else{
      return 0.5
    }
  },[data?.amount])

  const number = useMemo(()=>{
    if(data){
      return 16
    }else{
      return 4
    }
  },[data])

  const choose = useStore(s => s.choose)
  const search = useStore(s => s.search)
  const [hovered, hover] = useState(false)
  useCursor(hovered)

  const clicked = () =>{
    if(choose){
      if(choose.transaction_signature === data?.transaction_signature)
        useStore.setState({choose:undefined})
      else
        useStore.setState({choose:data})
    }
    else{
      useStore.setState({choose:data})
    }
  }

  useEffect(()=>{
    if(search === data?.transaction_signature){
      useStore.setState({choose:data})
    }
  },[search, data])
  const materialRef = useRef<THREE.MeshLambertMaterial>(null!)

  useFrame(({ clock }) => {
    const time = clock.getElapsedTime();
    const brightness = (choose && data && choose?.transaction_signature === data.transaction_signature)
      ?(Math.sin(time*2) * 0.25 + 0.5):(Math.sin(time * 2 + offset) * 0.1 - 0.1); // Range: 0 to 1
    if (materialRef.current) {
      materialRef.current.emissive.setScalar(brightness); // Set emissive brightness
    }
  });

  return (
    <mesh position={pos} name={data?.transaction_signature} userData={data} frustumCulled = {true} 
      onPointerOver={(e) => (e.stopPropagation(), data && hover(true))}
      onPointerOut={() => hover(false)}
      onClick={(e) => (e.stopPropagation(), data && clicked())}
    >
      <sphereGeometry args={[r, number, number]} />
      <meshLambertMaterial ref={materialRef}
        // color={ (choose && data && choose?.transaction_signature === data.transaction_signature) ? 0xffffff : color}
        color = {color}
      />
    </mesh>
  )
}

export default Star