/**
 * A container for components
 * Any component can be a child for this container
 */
import React, { useEffect, useState, cloneElement } from "react";
import classNames from "classnames";

const focusable = ["input", "select", "textarea", "button"];

export type Props = {
  /**
   * Container's children
   */
  children?: React.ReactNode | React.ReactNode[];
} & React.HTMLProps<HTMLDivElement>;

const Inputgroup = ({ children, className }: Props) => {
  const [focused, setFocused] = useState(false);
  useEffect(() => {}, [focused]);
  const arrChildren = React.Children.toArray(children);

  return (
    <form
      className={classNames(
        "border border-gray-200 rounded flex items-center p-1 m-4",
        focused ? "border-gray-900" : "border-gray-300",
        className
      )}
    >
      {arrChildren.map((e) => {
        if (
          React.isValidElement(e) &&
          typeof e.type === "string" &&
          focusable.includes(e.type)
        ) {
          return cloneElement(e as React.ReactComponentElement<"input">, {
            onFocus: (event: any) => {
              setFocused(true);
              e.props.onFocus && e.props.onFocus(event);
            },
            onBlur: (event: any) => {
              setFocused(false);
              e.props.onBlur && e.props.onBlur(event);
            },
          });
        }
        return e;
      })}
    </form>
  );
};

export default Inputgroup;
