import React, { useState } from 'react';
import { Box } from '../Box';
import { TouchableWithoutFeedback, StyleSheet } from 'react-native';
import { useTheme } from '../../theme/ThemeProvider';
import FillCheckIcon from '../../icons/FillCheckIcon';
import { Normalize } from '../../utils/normalize';
import type { Theme } from '../../theme/theme';

type Props = {
  onPress?: () => void;
  checked: boolean;
  disabled?: boolean;
  focus?: boolean;
  radio?: boolean;
};

function getBackgroundColor(
  disabled: Props['disabled'],
  checked: Props['disabled'],
  colors: Theme['colors']
) {
  if (disabled) {
    return colors.gray100;
  }

  if (checked) {
    return colors.green;
  }

  return colors.yankeesBlue;
}

export const CheckBox = ({
  onPress = () => null,
  checked = false,
  disabled = false,
  focus = false,
  radio = false,
}: Props) => {
  const [onFocus, setOnFocus] = useState(focus);
  const { colors } = useTheme();
  const borderRadius = radio ? Normalize(50) : Normalize(4);
  return (
    <TouchableWithoutFeedback
      onPress={onPress}
      disabled={disabled}
      onBlur={() => setOnFocus(false)}
      onFocus={() => setOnFocus(true)}
      onPressIn={() => setOnFocus(true)}
      onPressOut={() => setOnFocus(false)}
      testID="testCheckBox"
    >
      <Box
        flexDirection="row"
        alignItems="center"
        justifyContent="center"
        width={28}
        height={28}
        borderRadius={borderRadius}
        style={{
          borderColor: onFocus ? colors.greenWithOpacity : colors.transparent,
        }}
        borderWidth={Normalize(4)}
      >
        <Box
          padding="spacing-xxxs"
          width={20}
          height={20}
          borderRadius={borderRadius}
          style={{
            backgroundColor: getBackgroundColor(disabled, checked, colors),
          }}
        >
          {checked ? (
            <Box style={styles.selectedUI}>
              <FillCheckIcon style={styles.checkboxTickImg} />
            </Box>
          ) : (
            <Box
              style={[styles.uncheckedCheckbox, { borderRadius: borderRadius }]}
            />
          )}
        </Box>
      </Box>
    </TouchableWithoutFeedback>
  );
};

const styles = StyleSheet.create({
  selectedUI: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingRight: 1,
  },
  checkboxTickImg: {
    width: '100%',
    height: '100%',
    tintColor: '#ffffff',
    resizeMode: 'contain',
  },
  uncheckedCheckbox: {
    flex: 1,
    backgroundColor: '#ffffff',
  },
});
