import { Stack, Typography, useTheme } from '@mui/material';

import Avatar from '../../Avatar';
import RadioBase from '../RadioBase';

import { type RadioButtonProps } from './types';
import { getLabelColor, getSecondaryTextColor } from './utils';

const RadioButton: React.FC<RadioButtonProps> = ({
  error = false,
  disabled = false,
  isActive = false,
  label,
  extraData,
  description,
  onClick = () => {},
  stackSx = {},
  labelProps = {},
  avatarProps,
  ...props
}) => {
  const theme = useTheme();

  const labelColor = getLabelColor(theme, disabled, error);
  const secondaryTextColor = getSecondaryTextColor(theme, disabled);

  const handleClick = () => !disabled && onClick(!isActive);

  return (
    <Stack
      sx={{
        alignItems: avatarProps ? 'center' : 'flex-start',
        flexDirection: 'row',
        gap: 0.5,
        cursor: 'pointer',
        ...stackSx,
      }}
      onClick={handleClick}
    >
      <RadioBase
        {...props}
        disabled={disabled}
        checked={isActive}
        error={error}
      />
      {avatarProps && (
        <Avatar
          sx={{ ml: 1.5, mr: 0.5 }}
          {...avatarProps}
        />
      )}
      <Stack
        component="label"
        sx={{ gap: '2px', cursor: 'pointer' }}
      >
        <Stack
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
            flexDirection: 'row',
            gap: '4px',
          }}
        >
          <Typography
            variant="globalS"
            sx={{
              color: labelColor,
              minWidth: '200px',
            }}
            {...labelProps}
          >
            {label}
          </Typography>
          {extraData && (
            <Typography
              variant="globalXS"
              sx={{
                color: secondaryTextColor,
              }}
            >
              {extraData}
            </Typography>
          )}
        </Stack>
        {description && (
          <Typography
            variant="globalXS"
            sx={{
              color: secondaryTextColor,
            }}
          >
            {description}
          </Typography>
        )}
      </Stack>
    </Stack>
  );
};

export type { RadioButtonProps };

export default RadioButton;
