import React, { HTMLProps, ReactNode, useContext, useState } from "react";
import classNames from "classnames";
import { Box, BoxProps } from "../Box";
import { Divider } from "../Divider";
import { FormGroupContext } from "./FormGroupContext";
import { STATUS_VARIANT, THEME } from "../../types";
import { bem } from "../../utilities/bem";
import { ThemeContext } from "../../contexts";

const cn = "FormGroup";

interface FormGroupProps extends BoxProps {
  isRequired?: boolean;
  hasDivider?: boolean;
  id?: string;
  variant?: STATUS_VARIANT;
  theme?: THEME;
  children: ReactNode;
}

export const FormGroup = (props: FormGroupProps) => {
  const {
    children,
    isRequired,
    hasDivider,
    id,
    variant,
    theme: themeProp,
    className,
    ...rest
  } = props;
  const themeContext = useContext(ThemeContext);
  const theme = themeProp || themeContext;
  const [hasLabel, setHasLabel] = useState(false);
  const [labelProps, setLabelProps] = useState<
    Partial<HTMLProps<HTMLLabelElement>>
  >({});

  return (
    <FormGroupContext.Provider
      value={{
        id,
        variant,
        theme,
        isRequired,
        hasLabel,
        setHasLabel,
        setLabelProps,
        labelProps,
      }}
    >
      <Box className={classNames(bem(cn), className)} {...rest}>
        {hasDivider && <Divider className="my-5" />}
        {children}
      </Box>
    </FormGroupContext.Provider>
  );
};
