import { Field, FieldArray } from "formik";
import React from "react";
import { useSelector } from "react-redux";
import { State } from "../../types";
import { QuantityData } from "../../../api";

interface Props {
  name: string;
  values: QuantityData[];
}

export default function RecipeIngredients({ name, values }: Props) {
  const ingredients = useSelector((state: State) => state.entities.ingredients);
  return (
    <FieldArray name={name}>
      {({ remove, push }) => (
        <div>
          <table>
            <thead>
              <tr>
                <th />
                <th>Имя ингредиента</th>
                <th>Количество (граммы)</th>
              </tr>
            </thead>
            <tbody>
              {values.map((_, index) => (
                <tr key={index}>
                  <td>
                    <button
                      type="button"
                      className="secondary"
                      onClick={() => remove(index)}
                    >
                      X
                    </button>
                  </td>
                  <td>
                    <Field as="select" name={`${name}.${index}.ingredientId`}>
                      {Object.keys(ingredients).map((key) => (
                        <option key={key} value={key}>
                          {key}
                        </option>
                      ))}
                    </Field>
                  </td>
                  <td>
                    <Field
                      name={`${name}.${index}.quantity`}
                      placeholder="Кол-во"
                      type="number"
                      step="0.01"
                    />
                  </td>
                </tr>
              ))}
              <tr>
                <td colSpan={3}>
                  <button
                    type="button"
                    className="secondary"
                    onClick={() =>
                      push({
                        ingredientId: Object.keys(ingredients)[0],
                        quantity: 0,
                      })
                    }
                  >
                    Добавить ингредиент
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      )}
    </FieldArray>
  );
}
