import { Grid, Typography } from "@mui/material";
import { useEffect, useState } from "react";
import { WordsContext } from "../Context/WordsContext";
import CreateWordEmbedding from "../CreateWord/CreateWord";
import WordCard from "../WordCard";
import EmbeddingPlot from "../Plot";

export default function ActiveWords() {
  const [words, setWords] = useState([]);
  // const [embedding, setEmbedding] = useState([]);

  const fetchWords = async () => {
    const response = await fetch("http://localhost:8000/api/words");
    const wordsResponse = await response.json();
    setWords(wordsResponse.data);

    // console.log("response", wordsResponse.data);
    // console.log("words", words);
    
  };

  const deleteWord = async (id) => {
    await fetch(`http://localhost:8000/api/delete-word/${id}`, {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
    });
    await fetchWords();
  };

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

  return (
    <>
      <WordsContext.Provider value={{ words, fetchWords }}>
        <Grid container>
          <Grid item xs={8} container direction={"column"}>
            <Grid item>
              <CreateWordEmbedding />
            </Grid>
            <Grid item>
              <EmbeddingPlot words={words}/>
            </Grid>
          </Grid>
          <Grid item xs={4}>
            <Grid item>
              <Typography variant={"h4"}>Active Words</Typography>
            </Grid>
            <Grid container direction={"column"} mt={2}>
              {words.map((word) => (
                <Grid item key={word.id} mb={1} mr={1}>
                  <WordCard
                    word={word.item}
                    id={word.id}
                    deleteWord={deleteWord}
                  />
                </Grid>
              ))}
            </Grid>
          </Grid>
        </Grid>
      </WordsContext.Provider>
    </>
  );
}
