import { useEffect, useMemo, useState } from "react";
import * as THREE from "three"
import axios from 'axios';
import Constellation from "./Constellation";
import { supabase } from "@/lib/supabaseClient";

export default function Network() {

  const [netWork, setNetWork] = useState<any[] | undefined>(undefined);

  const fetchData = async () => {
    const { data, error } = await supabase.from('transaction-data').select('*'); // Specify columns or use '*' for all columns  
    if (error) {
      console.error('Error fetching data:', error);
      return 
    }
    const response= await axios.get('/api/stars-dataset')
    const names = response.data
    data.sort((a,b)=>b.time - a.time)
    const tempNetwork = []
    const keys :any = {}
    let k = 0, x = -k, y = -k, z = -k
    for (let i = 0; i< 343;i++){
      const constellation = [data[i*5], data[i*5+1], data[i*5+2], data[i*5+3], data[i*5+4]]
      while (true){
        const _key = `${x},${y},${z}`
        if(!keys[_key]){
          keys[_key] = true
          tempNetwork.push(
            {
              position:new THREE.Vector3(x*65, y*65, z*65),
              stars : constellation,
              name : i % 1 ===0 ? names[Math.floor(Math.random()*335)] : undefined
            }
          )
          break
        }
        z++
        if(z>k){
          y++
          z = -k
          if(y>k){
            x++
            y = z = -k
            if(x>k){
              k ++
              x = y = z = -k
            }
          }
        }
      }
    }
    setNetWork(tempNetwork);
    return ;
  };

  useEffect(() => {
    fetchData()
  }, []);

  return (
    <group name="network">
      {
        netWork &&
        netWork.map((item, index)=><Constellation key={index} data={item}/>)
      }
    </group>
  )
}