
import useStore from '@/lib/store';
import React, { useEffect, useRef, useState } from 'react'
import Styles from "./styles.module.scss"
import { supabase } from '@/lib/supabaseClient';
import SearchResults from './SearchResults';
import RecentTXNs from './RecentTXNs';
import starData from "@/components/MyScene/Chunk/data.json"
import Notifications from './Notifications';

export default function BottomPanel({flag, changeFlag}:{flag:boolean, changeFlag(value:boolean):void}) {

  const [results, setResults] = useState<any[] | undefined>(undefined)
  const ref = useRef<HTMLDivElement>(null);
  const [Observatory, setObservatory] = useState({stars:0, constellations:0, wallets:0})
  const [recentTXNs, setRecentTXNs] = useState<any[] | undefined>(undefined)
  const [latestConstellations, setLatestConstellations] = useState<string[]>([])
  const names = starData.names
  const tutorial = useStore((s)=>s.tutorial)
  const tabs = useStore((s)=>s.tabs)

  const fetchTableData = async (tableName: string, filter?: string) => {
    try {      
      const { data, error } = await supabase.from(tableName).select('*').or(`transaction_signature.eq.${filter}, from_address.eq.${filter}`);
      // 5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1
      if (error) {
        throw new Error(error.message);
      }  
      return data;
    } catch (error) {
      console.error('Error fetching data:', error);
      throw error;
    }
  };

  const handleKeyDown = async (event: any) => {
    if (event.key === 'Enter') {
      if(event.target.value !== ""){
        const data = await fetchTableData('transaction-data-updated', event.target.value)
        setResults(data)
      }
    }
  };

  const changeInput = async (value: string) => {
    if(value === ""){      
      setResults(undefined)
      useStore.setState({choose:undefined})
    }
  };

  const fetchDataForObservatory = async () =>{
    try {      
      const { data, error } = await supabase.from("transaction-data-updated").select('*').order('transaction_id', { ascending: false });
      // 5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1
      if (error) {
        console.log(error.message)
        throw new Error(error.message);
      }
      if(data.length>0){
        const stars = data.length
        const constellations = Math.floor((stars-1)/5)+1
        const temp : string[] = []
        setRecentTXNs(data.slice(0, 15))
        data.map((item)=>{
          if(!temp.includes(item["from_address"]))
            temp.push(item["from_address"])
        })
        const wallets = temp.length
        setObservatory({stars, constellations, wallets})
        const tempLatestConstellations : string[] = []
        data.slice(0, 15).map((item)=>{
          const k = Math.floor((item.transaction_id-1)/5)
          if(!tempLatestConstellations.includes(names[k])){
            tempLatestConstellations.push(names[k])
          }
        })
        setLatestConstellations(tempLatestConstellations)
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      throw error;
    }
  }

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

  useEffect(()=>{
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        !tutorial && useStore.setState({tabs:0});
      }
    };
    if(!tutorial){
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }

  },[tutorial])

  const changeTabs = (value:number) =>{
    useStore.setState({tabs:value})
  }
  
  return (
    <React.Fragment>      
      <div ref={ref} className={(tabs === 1 || tabs === 3)?`${Styles.bottomPanel} ${Styles.activePanel}`:Styles.bottomPanel}>
        <div className='relative w-full h-fit'>
          <div className={Styles.tabs}>
            <div className={tabs===1?`${Styles.tab} ${Styles.active}`:Styles.tab} onClick={()=>changeTabs(1)}>
              <div className={Styles.text}>
                Search
              </div>
            </div>
            <div className={tabs===2?`${Styles.tab} ${Styles.active}`:Styles.tab} onClick={()=>changeTabs(2)}>
              <div className={Styles.text}>
              Stellar Births
              </div>
            </div>
            <div className={tabs===3?`${Styles.tab} ${Styles.active}`:Styles.tab} onClick={()=>changeTabs(3)}>
              <div className={Styles.text}>
              Celestial Observatory
              </div>
            </div>
          </div>

          <div className='flex justify-end p-4'>
            {
              tabs === 1 ?
              <div className={Styles.wrapper}>
                <div className={Styles.inputContainter}>
                  <input type='search' placeholder='transaction signature | wallet address' onKeyDown={handleKeyDown} onChange={(e)=>changeInput(e.target.value)}/>
                </div>
              </div>
              : tabs === 3 ?
              <div className='flex gap-12'>
                <div className={Styles.wrapper}>
                  <div className={Styles.inputContainter}>
                    <p>
                      {Observatory.stars} Stars
                    </p>
                  </div>
                </div>
                <div className={Styles.wrapper}>
                  <div className={Styles.inputContainter}>
                    <p>
                      {Observatory.constellations} Constellations
                    </p>
                  </div>
                </div>
                <div className={Styles.wrapper}>
                  <div className={Styles.inputContainter}>
                    <p>
                      {Observatory.wallets} Cosmic Nurturers
                    </p>
                  </div>
                </div>
              </div>
              :
              <div className={`${Styles.wrapper} hidden`}>
                <div className={Styles.inputContainter}>
                  <div>

                  </div>
                </div>
              </div>
            }
          </div>
          
        {
          latestConstellations?.length>0 &&  <Notifications data={latestConstellations}/>
        }
        </div>
        <SearchResults results={results} setResults={setResults}/>
        <RecentTXNs tabs={tabs} data={recentTXNs} setTabs={changeTabs}/>
      </div>
    </React.Fragment>
  )
}