import React, { useEffect, useState } from "react";
import { Box, Text, UseInput } from "./Ink";
import {
  ConfiguredFilter,
  Filter,
  FiltersPicker as ChildFiltersPicker,
} from "./Filter";
import { Entity, entityToTable } from "../ZQueryBuilder";
import { useKeyboardShortcuts } from "./KeyboardShortcuts";

const API_ENDPOINT = process.env.API_ENDPOINT ?? "https://api.zygon.tech";

type FiltersPickerProps = {
  entity: Entity;
  width: number;
  height: number;
  onFiltersSelection: (filters: Array<ConfiguredFilter>) => void;
  useInput: UseInput;
  apiKey: string;
};

export const FiltersPicker = ({
  entity,
  width,
  height,
  onFiltersSelection,
  useInput,
  apiKey,
}: FiltersPickerProps) => {
  useKeyboardShortcuts({
    upArrow: { name: "Previous item" },
    downArrow: { name: "Next item" },
    space: { name: "Select item" },
    return: { name: "Validate selection" },
  });

  const [filters, setFilters] = useState<null | Array<Filter>>(null);

  useEffect(() => {
    fetch(`${API_ENDPOINT}/zquery/${entityToTable(entity)}/filters`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((filters) => setFilters(filters as Array<Filter>));
  }, []);

  return (
    <Box flexDirection="column" width={width} height={height}>
      <Text>Pick the filters for the query:</Text>
      {filters && (
        <ChildFiltersPicker
          width={width}
          height={height - 4}
          filters={filters}
          onFiltersSelection={onFiltersSelection}
          useInput={useInput}
        />
      )}
    </Box>
  );
};
