import { forwardRef } from 'react';

import { Pressable, View } from 'react-native';
import { Container } from '@cleartrip/ct-design-container';
import { Typography, TypographyVariant } from '@cleartrip/ct-design-typography';
import { makeStyles, useNativeMergeStyles, useStyles } from '@cleartrip/ct-design-style-manager';
import { useTheme } from '@cleartrip/ct-design-theme';

import { getBorderStyles, getLabelColor } from './style';
import { IRadio } from './type';

const staticRadioStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    gap: theme?.spacing[2],
  },
  radioBtn: {
    width: theme?.spacing[5],
    height: theme?.spacing[5],
    borderRadius: theme?.border.radius[32],
    borderStyle: theme?.border.style.solid,
  },
}));

const Radio = forwardRef<View, IRadio>(
  (
    { id, label, labelCTA, labelVariant, onChange, disabled = false, checked = false, styleConfig, rootProps = {} },
    ref,
  ) => {
    const theme = useTheme();

    const radioBtnStyles = useStyles(
      (themeArg) => ({
        root: getBorderStyles(themeArg, checked, disabled),
      }),
      [disabled, checked],
    );

    const {
      root: customRootStyles = [],
      radioBtn: customRadioBtnStyles = [],
      labelContainer: customLabelContainerStyles = [],
    } = styleConfig || {};

    const mergedRootStyles = useNativeMergeStyles([staticRadioStyles?.root, ...customRootStyles], [customRootStyles]);

    const handleOnRadioClick = () => {
      if (disabled) return;
      onChange?.();
    };

    return (
      <Pressable
        hitSlop={{ top: theme?.spacing[3], bottom: theme?.spacing[3] }}
        ref={ref}
        id={id}
        style={mergedRootStyles}
        disabled={disabled}
        onPress={handleOnRadioClick}
        {...rootProps}
      >
        <Container
          styleConfig={{ root: [staticRadioStyles?.radioBtn, radioBtnStyles.root, ...customRadioBtnStyles] }}
          onClick={handleOnRadioClick}
        />
        <Container styleConfig={{ root: [...customLabelContainerStyles] }} onClick={handleOnRadioClick}>
          {typeof label === 'string' ? (
            <Typography variant={TypographyVariant.B2} color={getLabelColor(disabled)}>
              {label}
            </Typography>
          ) : (
            label
          )}
          {typeof labelCTA === 'string' ? (
            <Typography variant={labelVariant || TypographyVariant.B2} color={getLabelColor(disabled)}>
              {labelCTA}
            </Typography>
          ) : (
            labelCTA
          )}
        </Container>
      </Pressable>
    );
  },
);

Radio.displayName = 'Radio';

export default Radio;
