import React from "react";
import { Input, Button } from "antd";
import { useFormikContext } from "formik";
import { useTranslation } from "react-i18next";

interface FieldGroupProps {
  array_name: string;
  title:string;
  static?: boolean;
  only_value?: boolean;
}

const FieldGroup: React.FC<FieldGroupProps> = ({ array_name ,title,static:isStatic,only_value}) => {
  const { values, setFieldValue } = useFormikContext<any>();
  const addFieldGroup = () => {
    setFieldValue(array_name, [
      ...(values?.[array_name] || []),
      { key: null, value: null },
    ]);
  };
  const deleteFieldGroup = () => {
    const updatedArray = values?.[array_name]?.slice(0, -1) || [];
    setFieldValue(array_name, updatedArray);
  };


  const handleChangeKey = (
    e: React.ChangeEvent<HTMLInputElement>,
    index: number
  ) => {
    const Selects = values?.[array_name] ?? [];
    Selects[index].key = e.target.value;
    setFieldValue(array_name, Selects);
  };

  const handleChangeValue = (
    e: React.ChangeEvent<HTMLInputElement>,
    index: number
  ) => {
    const Selects = values?.[array_name] ?? [];
    Selects[index].value = e.target.value;
    setFieldValue(array_name, Selects);
  };

  const selectsArray = values?.[array_name] ?? [];
  const { t } = useTranslation();

  return (
    <>
    <label htmlFor={array_name} className="text">
    <h5 className="mb-2">{t(title)}</h5>
        </label>
      {selectsArray.map((group: { key: string; value: string }, index: number) => (
        <div key={index} className="d-flex gap-2 mb-3">
          <Input
            placeholder={t("key")}
            onChange={(e) => handleChangeKey(e, index)}
            value={group.key}
            size="large"
            style={{ width: "100%" }}
            allowClear
            disabled={only_value}
          />
          <Input
            placeholder={t("value")}
            onChange={(e) => handleChangeValue(e, index)}
            value={group.value}
            size="large"
            style={{ width: "100%" }}
            allowClear
            
          />
        </div>
      ))}
      {!isStatic &&
  <div className="d-flex gap-2">
  <Button
    type="dashed"
    onClick={addFieldGroup}
  >
    {t("add_new")}
  </Button>
  <Button
    type="dashed"
    onClick={deleteFieldGroup}
  >
    {t("delete_last")}
  </Button>
  </div>
      }
    
    </>
  );
};

export default FieldGroup;
