import { FieldArray as FormikFieldArray } from "formik";
import React from "react";

import theme from "mazlo-theme";

import { Button } from "../Button";
import { View } from "../View";
import styles from "./styles";

type Props = {
  itemPadding?: number;
  maxItems?: number;
  name?: string;
  onAdd: () => any;
  renderItem: (params: { item: any; index: number }) => React.ReactNode;
  value?: any[];
  buttonTitleAdd?: string;
};

const FormArray = ({
  itemPadding = theme.space[4],
  maxItems,
  name,
  onAdd,
  renderItem,
  value,
  buttonTitleAdd = "Add New",
}: Props) => {
  return (
    <FormikFieldArray name={name}>
      {(arrayHelpers) => (
        <View style={styles.container}>
          {value &&
            value.length > 0 &&
            value.map((item, index) => (
              <View
                key={index}
                style={[styles.itemContainer, { padding: itemPadding }]}
              >
                {renderItem({ item, index })}
                <View style={styles.buttonContainer}>
                  <Button
                    title="x"
                    onPress={() => arrayHelpers.remove(index)}
                    style={styles.button}
                  />
                  {index > 0 && (
                    <Button
                      title="^"
                      onPress={() => arrayHelpers.move(index, index - 1)}
                      style={styles.button}
                    />
                  )}
                  {index < value.length - 1 && (
                    <Button
                      title="v"
                      onPress={() => arrayHelpers.move(index, index + 1)}
                      style={styles.button}
                    />
                  )}
                </View>
              </View>
            ))}

          {(!maxItems ||
            (maxItems && value?.length && maxItems > value.length)) && (
            <View style={styles.addButtonContainer}>
              <Button
                title={buttonTitleAdd}
                onPress={() => arrayHelpers.push(onAdd())}
              />
            </View>
          )}
        </View>
      )}
    </FormikFieldArray>
  );
};

export default FormArray;
