import React, {
  createContext,
  useCallback,
  useContext,
  useState,
  Fragment,
} from 'react';
import type { FlexProps } from '../atoms';
import { Flex, Radio, RadioCards } from '../atoms';

type RadioButtonCardRootProps = RadioCards.RootProps & {
  justify?: FlexProps['justify'];
  RadioWrapper?: React.FC;
};
const RadioCardContext = createContext<RadioButtonCardRootProps>({});

function Root(props: RadioCards.RootProps): React.ReactElement {
  const [value, setValue] = useState(props.value || props.defaultValue);

  const onValueChange = useCallback(
    (v: string) => {
      setValue(v);
      props.onValueChange?.(v);
    },
    [props]
  );

  return (
    <RadioCardContext.Provider value={{ ...props, value }}>
      <RadioCards.Root {...props} onValueChange={onValueChange} />
    </RadioCardContext.Provider>
  );
}

type RadioButtonCardItemProps = RadioCards.ItemProps;
function Item({
  children,
  ...itemRest
}: RadioCards.ItemProps): React.ReactElement {
  const {
    value,
    justify,
    RadioWrapper = Fragment,
    ...rootRest
  } = useContext(RadioCardContext);

  return (
    <RadioCards.Item {...itemRest}>
      <Flex align="center" justify={justify || 'between'} width="100%">
        {children}
        <RadioWrapper>
          <Radio
            checked={itemRest.value === value}
            disabled={rootRest.disabled}
            value={itemRest.value}
          />
        </RadioWrapper>
      </Flex>
    </RadioCards.Item>
  );
}

export const RadioButtonCard = {
  Root,
  Item,
};

export type { RadioButtonCardItemProps, RadioButtonCardRootProps };
