import * as Ariakit from '@ariakit/react';
import { ComponentPropsWithRef, forwardRef, useContext } from 'react';
import styled from 'styled-components';
import { UIComponentWithRef } from '../../components/types';
import { getVariantKey, useVariants } from '../../variants';
import { RadioContext } from './radio.context';
import { IRadioVariants, radioVariants } from './radio.variants';

type Props = {
  variant?: keyof typeof radioVariants | (string & {});
  variants?: IRadioVariants;
};

// export type RadioGroupProps = UIStyledComponentProps<Props, 'input'>;

const StyledRadioGroup = styled(Ariakit.Group) <Ariakit.GroupProps & Props>`
  ${props => getVariantKey('group', props.variant, props.variants)}
`;

type RadioGroupComponent<C extends React.ElementType = 'div'> = UIComponentWithRef<C, Ariakit.RadioProviderProps & Props>;

export const RadioGroup: RadioGroupComponent = forwardRef<HTMLDivElement, RadioGroupProps>(
  function RadioGroup({
    variant = 'default',
    variants,
    defaultValue,
    value,
    setValue,
    store,
    children,
    ...props
  }, ref) {
    const context = useContext(RadioContext);
    const globalVariants = useVariants('radio', radioVariants);
    variants = variants || globalVariants;
    return (
      <Ariakit.RadioProvider
        defaultValue={defaultValue}
        value={value}
        setValue={setValue}
        store={store}
      >
        <RadioContext.Provider value={{
          variant,
          variants,
        }}>
          <StyledRadioGroup
            ref={ref}
            variant={variant || context?.variant}
            variants={variants || context?.variants}
            {...props}
          >
            {children}
          </StyledRadioGroup>
        </RadioContext.Provider>
      </Ariakit.RadioProvider>
    );
  }
);

export type RadioGroupProps = ComponentPropsWithRef<typeof RadioGroup>;
