
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';

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 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})
    }
  };
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        changeFlag(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);
  
  return (
    <React.Fragment>      
      <div ref={ref} className={flag?`${Styles.bottomPanel} ${Styles.activePanel}`:Styles.bottomPanel}>
        <div className='relative w-full h-fit'>
          <div className={Styles.tabs}>
            <div className={Styles.tab} onClick={()=>changeFlag(!flag)}>
              <div className={Styles.text}>
                Search
              </div>
            </div>
          </div>

          <div className='flex justify-end p-4'>
            <div className={Styles.search}>
              <div className={Styles.inputContainter}>
                <input type='search' placeholder='transaction signature | wallet address' onKeyDown={handleKeyDown} onChange={(e)=>changeInput(e.target.value)}/>
              </div>
            </div>
          </div>
        </div>
        <SearchResults results={results} setResults={setResults}/>
      </div>
    </React.Fragment>
  )
}