import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { faPlus, faTimes } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useFieldArray } from "react-hook-form";
import { RenderElement } from "..";

export default function DynamicElement({ form, element, upperLabel }) {
  const {
    fields: dynamicFields,
    append,
    remove,
  } = useFieldArray({
    control: form.control,
    name: element.name,
  });

  return (
    <div className="flex w-full gap-2">
      <div className="grow space-y-4">
        {dynamicFields.map((item, index) => (
          <div className="flex w-full gap-2" key={item.id}>
            {element.fields.map((fieldGroup: any, groupIndex: number) => (
              <div className={cn("grow", element.className)} key={groupIndex}>
                {fieldGroup.map((fieldItem: any, fieldIndex: number) => {
                  fieldItem.name = `${element.name}[${index}].${fieldItem.name}`;
                  return RenderElement({
                    element: fieldItem,
                    form,
                    index,
                    upperLabel,
                  });
                })}
              </div>
            ))}
            <Button
              variant="plain"
              color="danger"
              size="xs"
              type="button"
              onClick={() => remove(index)}
              disabled={dynamicFields.length <= 1}
            >
              <FontAwesomeIcon icon={faTimes} />
            </Button>
          </div>
        ))}
      </div>
      <div className="flex">
        <Button
          variant="solid"
          color="primary"
          size="xs"
          type="button"
          onClick={() => append({})}
        >
          <FontAwesomeIcon icon={faPlus} />
        </Button>
      </div>
    </div>
  );
}
