import { useEffect, useState } from "react";
import "./App.css";
import { processData, searchByText, searchByTheme, processTheme } from "./utils/parsing";
import Graph from "./components/graph";
import { processRawFiles } from "./utils/agent";


const files=['大家想到未來不會很絕望嗎','日常生活','有人懂嗎','看到學貸還款通知書寄來','租屋網站'];
const ContentTags=['Summary','Keywords','Order','User','Content'];
const DisplayTypes=['text','point'];

function App() {

  const [themes, setThemes]=useState([]);
  const [results, setResults]=useState([]);
  const [selectTab, setSelectTab]=useState('text');

  function preText(){
    
    files.forEach(async (file)=>{
      const url = `assets/collect/${file}.json`;
      await processData(url);
    });
    
  }
  function preTheme(){
    if(themes?.length>0)
      processTheme(themes);          
  }
  function processRaw(){
     processRawFiles('resources/raw/1222', 'resources/collect/1222');
  }

  useEffect(()=>{
    
    fetch('themes.json').then(response=>response.json()).then(async (json)=>{
      console.log(json);
      setThemes(json);      
    });

  },[]);

  return (
    <main className="flex flex-col justify-center gap-2 p-4">
      <div>
        <button onClick={processRaw}>process raw files</button>
        <button onClick={preText}>add data embedding</button>
        <button onClick={preTheme}>reset theme embedding</button>
      </div>
      <p id="embeddings"></p>

      <form>
        <p>search by any text</p>
        <input type="text" name="query" placeholder="Enter your query" />      
        <button type="button" onClick={()=>{
            const query = document.querySelector('input[name="query"]').value;
            searchByText(query).then(res=>{
                setResults(res);
            });
        }}>
          Search
        </button> 
      </form>
      <form>
        <p>search by theme</p>
        <select name="collection">
          {themes.map((theme, index)=>(
            <option key={index} value={theme.id}>{theme.title} [{theme.keywords.join(", ")}]</option>
          ))}
        </select>
        <button type="button" onClick={()=>{
            const collection = document.querySelector('select[name="collection"]').value;
            console.log("Selected collection:", collection);
            // const id=themes.find(item=>item.title===collection)?.id;
            searchByTheme(collection).then(res=>{
                setResults(res);
            });

        }}>
          Search
        </button>
      </form>
      <div>
        <div>Results={results?.length}</div>
        {DisplayTypes.map((type)=>(
          <button 
            key={type}
            onClick={()=>{
              setSelectTab(type);
            }}
            disabled={selectTab===type}
            className={selectTab===type ? 'bg-blue-500 text-white' : ''}
          >
            {type}
          </button>
        ))} 
      </div>
      {selectTab==='text' && (
        <div id="search-results">        
          {results?.length>0 && results.map((item, index)=>{
              let output={};
              
              return (
                <div key={index} className="border-b p-2 my-2 grid grid-cols-5 gap-2">                
                  {/* <p>score={item.score.toFixed(4)}</p> */}
                  {(()=>{
                    let p=JSON.parse(item.payload.text);
                    return (<>
                      <div>{p.number}/{p.total}</div>
                      <div className="col-span-2">{p.content}</div>
                      <div className="bg-pink-200 text-xs self-center">{p.summry}</div>                    
                      <div className="flex flex-row gap-2 flex-wrap items-center text-xs">{p.keywords.map(el=><span className="bg-gray-200 rounded-full px-2" key={el}>{el}</span>)}</div>
                    </>);
                  })()}
                </div>
              );
          })}
        </div>
        )}
      {selectTab==='point' && (
        <Graph results={results} />
      )}
    </main>
  );
}

export default App;
