import { FC, useCallback, useRef } from 'react';
import { Avatar } from 'components/avatar';
import { Col, Row, StyleSystemThemedProps, TouchableHighlight } from 'components/layout';
import { Text } from 'components/text';
import { metrics } from 'config';
import { useHover } from 'react-native-web-hooks';
import { Radio } from 'components/radio';
import { IconProps } from 'icons/types';
import { Visible } from 'components/visible';

const { STYLES } = metrics;

export const RadioItem: FC<RadioItemType> = ({
  avatarSize = 50,
  radioSize = 32,
  item,
  setRadioItem,
  isSelected,
  ...props
}) => {
  const typeRef = useRef(null);
  const isHovered = useHover(typeRef);
  const { title, Icon, caption, type } = item;
  const color = isSelected ? 'primary' : 'base-02';
  const iconColor = isSelected ? 'white' : 'body';
  const hoveredBackgroundColor = isHovered ? 'base-02-hover' : 'transparent';
  const backgroundColor = isSelected ? 'primary-03' : hoveredBackgroundColor;

  const handleRadioItem = useCallback(() => {
    setRadioItem(type);
  }, [setRadioItem, type]);

  const sizeVariant = radioSize ? undefined : 'small';

  return (
    <TouchableHighlight underlayColor={'transparent'} onPress={handleRadioItem}>
      <Row
        ref={typeRef}
        borderColor={color}
        borderWidth={1}
        flexGrow={1}
        flexShrink={1}
        px="xs"
        py="2xs"
        borderRadius={STYLES.radius.card}
        backgroundColor={backgroundColor}
        justifyContent="space-between"
        {...props}
      >
        <Row flexShrink={1}>
          <Avatar icon={<Icon colorVariant={iconColor} />} size={avatarSize} colorVariant={color} />
          <Col justifyContent="center" flexShrink={1} ml="s">
            <Text variant="body" color="title" weightVariant="bold">
              {title}
            </Text>
            <Visible if={!!caption}>
              <Text mt="3xs" variant="caption">
                {caption}
              </Text>
            </Visible>
          </Col>
        </Row>
        <Row ml="m">
          <Radio
            colorVariant={color}
            sizeVariant={sizeVariant}
            isActive={isSelected}
            size={radioSize}
          />
        </Row>
      </Row>
    </TouchableHighlight>
  );
};
export type RadioItemOptionsProps = {
  type: string;
  title: string;
  caption?: string;
  isSelected: boolean;
  Icon: (props: IconProps) => JSX.Element;
};
type RadioItemType = StyleSystemThemedProps & RadioItemProps;

export interface RadioItemProps {
  avatarSize: number;
  radioSize: number;
  setRadioItem: (value: string) => void;
  item: RadioItemOptionsProps;
  isSelected: boolean;
}
