import React, { useEffect, useCallback } from "react";
import { Accordion, Card } from "react-bootstrap";
import Parser from "html-react-parser";
import styles from "../styles/results.module.css";
import Axios from "axios";
import { useGlobal, useSearchData } from "../context";
import { OpenExternalLinkButton, FavoriteButton } from "../components";

const Results = (props) => {
  const { api, token } = useGlobal();
  const {
    documents,
    highlighting,
    activeDocument,
    setActiveDocument,
    setFavorite,
  } = useSearchData();
  const { setPdfPage } = props;

  useEffect(() => {
    if (documents.length > 0)
      setActiveDocument(activeDocument ? activeDocument : documents[0].id);
    if (activeDocument && activeDocument !== documents[0].id) {
      const activeCard = document.querySelector(".restore-" + activeDocument);
      if (activeCard) {
        activeCard.scrollIntoView();
        // window.scrollBy(0, -700);
      }
    }
    // eslint-disable-next-line
  }, []);

  const _cardBody = useCallback(
    (docId) => {
      const highlights = highlighting[docId];
      if (!highlights?.fetched) {
        return <div>Loading ...</div>;
      }
      return (
        <table>
          <tbody>{highlights.pages.map((page) => (
            <tr
              key={page[0]}
              className={styles.cardTr}
              style={{ textAlign: "left", cursor: "pointer" }}
              onClick={() => setPdfPage(page[0])}
            >
              <td style={{ padding: "3px 5px 3px 1px", textAlign: "center" }}>
                {page[0]}
              </td>
              <td style={{ padding: "3px 1px", overflowWrap: "anywhere", hyphens: "auto" }}>
                {Parser(page[1].join(" ... "))}
              </td>
            </tr>
          ))}</tbody>
        </table>
              //   <table>
              //   <tbody>{Object.keys(highlights.pages).map((page) => (
              //     <tr
              //       key={page}
              //       className={styles.cardTr}
              //       style={{ textAlign: "left", cursor: "pointer" }}
              //       onClick={() => setPdfPage(page)}
              //     >
              //       <td style={{ padding: "3px 5px 3px 1px", textAlign: "center" }}>
              //         {page}
              //       </td>
              //       <td style={{ padding: "3px 1px", overflowWrap: "anywhere", hyphens: "auto" }}>
              //         {Parser(highlights.pages[page].join(" ... "))}
              //       </td>
              //     </tr>
              //   ))}</tbody>
              // </table>
      );
    },
    [highlighting, setPdfPage]
  );

  const _getVal = useCallback(
    (doc, field) => {
      const hl = highlighting;
      if (hl && hl[doc.id] && hl[doc.id][field]) {
        return Parser(hl[doc.id][field][0]);
      }
      return doc[field];
    },
    [highlighting]
  );

  const _toggleActiveDocument = useCallback(
    (docId) => {
      setActiveDocument(docId === activeDocument ? null : docId);
    },
    [setActiveDocument, activeDocument]
  );

  const _starKlickHandler = useCallback(
    (index) => {
      Axios.put(
        api + "/favorite/" + documents[index].id,
        {},
        {
          headers: { "x-access-token": token },
        }
      ).then((res) => {
        setFavorite(index, res.data);
      });
    },
    [documents, api, token, setFavorite]
  );

  const _cards = useCallback(() => {
    return documents.map((doc, i) => (
      <Card key={doc.id}>
        <Card.Header
          style={{ cursor: "pointer" }}
          className={"restore-" + doc.id}
        >
          <div style={{ display: "flex", width: "100%" }}>
            <Card.Header
              // as={Card.Header}
              block={"true"}
              // eventKey={doc.id}
              onClick={_toggleActiveDocument.bind(null, doc.id)}
              style={{
                textAlign: "left",
                paddingRight: "5px",
                width: "100%",
                paddingBottom: "0",
                border: "0",
                backgroundColor: "transparent",
              }}
            >
              {doc["document"] && <span style={{ marginRight: "5px" }}>{_getVal(doc, "document")}</span>}
              {doc["title"] && <span style={{ marginRight: "5px" }}>{_getVal(doc, "title")}</span>}
              {doc["subtitle"] && <span style={{ marginRight: "5px" }}><i>{_getVal(doc, "subtitle")}</i></span>}
            </Card.Header>
            <OpenExternalLinkButton link={doc.cache} />
            <FavoriteButton isFavorite={doc.isFavorite} onClick={_starKlickHandler.bind(null, i)} />
          </div>
          <Card.Header
            // as={Card.Header}
            block={"true"}
            // eventKey={doc.id}
            onClick={_toggleActiveDocument.bind(null, doc.id)}
            style={{
              textAlign: "left",
              border: "0",
              paddingTop: "0",
              backgroundColor: "transparent",
            }}
          >
            <small>{_getVal(doc, "zusatz")}</small>
          </Card.Header>
        </Card.Header>
        <Accordion.Collapse eventKey={doc.id}>
          <Card.Body>{_cardBody(doc.id)}</Card.Body>
        </Accordion.Collapse>
      </Card>
    ));
  }, [documents, _cardBody, _getVal, _starKlickHandler, _toggleActiveDocument]);

  if (documents.length > 0) {
    return (
      <React.Fragment>
        <Accordion activeKey={activeDocument}>{_cards()}</Accordion>
      </React.Fragment>
    );
  } else return <React.Fragment></React.Fragment>;
};

export default Results;
