import React, { useEffect, useState } from "react";
import { Entity, entityToTable } from "../ZQueryBuilder";
import { Box, Text, UseInput } from "./Ink";
import { ScrollableText } from "./ScrollableText";
import { ConfiguredFilter } from "./Filter";
import { API_ENDPOINT } from "../../zygonApi";

type FieldsPickerProps = {
  entity: Entity;
  fields: Array<string>;
  filters: Array<ConfiguredFilter>;

  width: number;
  height: number;

  useInput: UseInput;
  apiKey: string;
};

export const QueryResults = ({
  entity,
  fields,
  filters,
  width,
  height,
  useInput,
  apiKey,
}: FieldsPickerProps) => {
  const [querying, setQuerying] = useState(true);
  const [result, setResult] = useState<null | Array<unknown>>(null);

  useEffect(() => {
    fetch(`${API_ENDPOINT}/zquery`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        table: entityToTable(entity),
        fields: fields,
        filters: filters,
      }),
    })
      .then((response) => response.json())
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      .then((result: any) => {
        setResult(
          result.data[
            `filtered${entityToTable(entity)
              .split("")
              .map((char, index) => (index === 0 ? char.toUpperCase() : char))
              .join("")}s`
          ],
        );
      })
      .finally(() => setQuerying(false));
  }, []);

  return (
    <Box flexDirection="column" width={width} height={height} gap={1}>
      <Text>
        zygon api list {entity} {fields.join(",")} {JSON.stringify(filters)}
      </Text>

      {querying && <Text>Fetching results...</Text>}
      {result && (
        <ScrollableText
          text={JSON.stringify(result, null, 2)}
          width={width}
          height={height - 2}
          useInput={useInput}
        />
      )}
    </Box>
  );
};
