import { FC } from "react";
/* eslint-disable no-underscore-dangle */
import { GetServerSideProps, GetServerSidePropsContext } from "next";
// import { Client } from "@opensearch-project/opensearch";
import { RawDataViewer } from "components/RawDataViewer";
import { VisualizationDetail } from "components/VisualizationDetail";
import { checkAuth } from "lib/checkAuth";
// import { createVisualization } from "lib/opensearch";

interface PreviewProps {
  visualization: any;
  visualizationType: string;
  data: any[];
}

const Preview: FC<PreviewProps> = ({
  visualization,
  visualizationType,
  data,
}) =>
  visualizationType === "rawData" ? (
    <RawDataViewer rows={data} height={750} />
  ) : (
    <VisualizationDetail {...visualization} />
  );

export default Preview;

export const getServerSideProps: GetServerSideProps = async (
  context: GetServerSidePropsContext
) => {
  const res: any = await checkAuth(context);

  if (res.redirect) {
    return res;
  }
  /*
  const {
    visualizationID,
    searchQuery,
    visualizationType = "table",
  } = context.query;

  const node = `https://${process.env.OPENSEARCH_USERNAME}:${process.env.OPENSEARCH_PASSWORD}@${process.env.OPENSEARCH_URL}`;
  const client = new Client({
    node,
    ssl: {
      rejectUnauthorized: false,
    },
  });
  res.props.visualizationType = visualizationType as string;

  if (visualizationType !== "rawData") {
    await createVisualization({
      id: visualizationID as string,
      query: await JSON.parse(decodeURI(searchQuery as string)),
      kind: visualizationType as string,
    });
    const rawResponse = await client.search({
      index: ".kibana_1",
      size: 200,
    });
    const response = rawResponse.body;

    const hits = response.hits.hits.filter(
      (hit) => hit._id.split(":")[1] === visualizationID[0]
    );
    const hit = hits[0];
    res.props.visualization = {
      id: hit._id.split(":")[1],
      title: hit._source.visualization.title,
      description: hit._source.visualization.description,
      url: `/app/visualize?security_tenant=global#/edit/${
        hit._id.split(":")[1]
      }?embed=true`,
    };
  }

  const rawQuery = await JSON.parse(decodeURI(searchQuery as string));
  const query = {
    bool: {
      should: [],
      must_not: [],
    },
  };

  if (rawQuery.impactedTechnology.values.length > 0) {
    rawQuery.impactedTechnology.values.forEach((value) => {
      query.bool.should.push({
        match: { technology: value },
      });
    });
  }
  console.log({ query });
  const dataResponse = await client.search({
    index: "demo_data",
    size: 200,
    body: { query },
  });
  console.log({ dataResponse });
  res.props.data = dataResponse.body.hits.hits.map((hit) => ({
    id: hit._id,
    ...hit._source,
  }));
  console.log({ data: res.props.data });
  console.log(res.props.data[0]);
  */
  return res;
};
