import React, { FC, useContext } from 'react';
import { Box } from '../../Box';
import { Flex } from '../../Flex';
import { Heading } from '../../Heading';
import { Paragraph } from '../../Paragraph';
import { SvgCheckmark } from '../../../assets/images/icons';
import { Context } from '../../RadioGroup/Context';
import * as sc from './styles';

export interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
  Asset: React.ComponentType<React.SVGAttributes<SVGElement>>;
  value: string;
  /** dsd
   * Specify whether the control is checked
   */
  checked?: boolean;
  name?: React.AllHTMLAttributes<HTMLInputElement>['name'];
  heading: React.ReactNode | string;
  description: React.ReactNode | string;
}

export const CardRadio: FC<Props> = props => {
  const {
    heading,
    description,
    Asset,
    checked: checkedProp,
    name: nameProp,
    ...otherProps
  } = props;
  const radioGroup = useContext(Context);
  let inputProps;
  let checked = checkedProp;
  let name = nameProp;

  if (radioGroup) {
    const { value, name: radioGroupName, ...radioGroupOtherProps } = radioGroup;

    if (typeof checked === 'undefined') {
      checked = radioGroup.value === props.value;
    }
    if (typeof name === 'undefined') {
      name = radioGroupName;
    }
    inputProps = radioGroupOtherProps;
  }

  return (
    <label>
      <sc.Input
        type="radio"
        checked={checked}
        name={name}
        {...inputProps}
        {...otherProps}
      />
      <sc.Card boxShadow={1} p={0} rounded>
        <Flex p="m" alignItems="flex-start">
          <sc.RadioIcon
            Asset={SvgCheckmark}
            scale={0.9}
            width={20}
            height={20}
            color="white"
            checked={checked}
          />
          <Box ml="m" mr="auto">
            <Heading variant="h5" mb={0} mt={-1}>
              {heading}
            </Heading>
            <Paragraph fontSize={1}>{description}</Paragraph>
          </Box>
          <sc.Media
            Asset={Asset}
            color={checked ? 'brandMain' : 'gray.2'}
            bg={checked ? 'brandLightest' : 'gray.1'}
            width={48}
            height={48}
            scale={0.7}
          />
        </Flex>
      </sc.Card>
    </label>
  );
};
