import React, { useEffect, useState } from "react";
import { Box, Text, UseInput } from "./Ink";
import { SelectableList } from "./SelectableList";
import { Entity, entityToTable } from "../ZQueryBuilder";
import { useKeyboardShortcuts } from "./KeyboardShortcuts";

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

type FieldsPickerProps = {
  entity: Entity;
  width: number;
  height: number;
  onFieldsSelection: (fields: Array<string>) => void;
  useInput: UseInput;
  apiKey: string;
};

export const FieldsPicker = ({
  entity,
  width,
  height,
  onFieldsSelection,
  useInput,
  apiKey,
}: FieldsPickerProps) => {
  const [fields, setFields] = useState<null | Array<string>>(null);
  const [selectedFields, setSelectedFields] = useState<Array<string>>([]);

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

  useInput((input, key) => {
    if (key.return) {
      if (selectedFields.length > 0) {
        onFieldsSelection(selectedFields);
      }
    }
  });

  useKeyboardShortcuts({
    upArrow: { name: "Previous item" },
    downArrow: { name: "Next item" },
    space: { name: "Select item" },
    return: { name: "Validate selection" },
  });

  return (
    <Box flexDirection="column" width={width} height={height}>
      <Text>Pick the fields to query:</Text>
      {fields && (
        <SelectableList
          width={width}
          height={height - 3}
          items={fields}
          item={{ key: (item) => item, label: (item) => item }}
          onItemSelected={(field) =>
            setSelectedFields(
              selectedFields.includes(field)
                ? selectedFields.filter(
                    (selectedField) => selectedField !== field,
                  )
                : [...selectedFields, field],
            )
          }
          selected={selectedFields}
          useInput={useInput}
        />
      )}
    </Box>
  );
};
