import React from 'react';
import {StyleProp, ViewStyle, View, Pressable} from 'react-native';
import {Typography} from '@components/_core/Typography';
import {
  useInputController,
  UseInputControllerProps,
} from '@components/_HuGo/Inputs';
import {useTheme} from '@shared/theme';

import {styles} from './styles';
import {Check, CheckProps} from './components/Check';

export interface CheckboxProps extends CheckProps {
  title?: string;
  style?: StyleProp<ViewStyle>;
  description?: string;
  extraData?: string;
  checkboxStyle?: StyleProp<ViewStyle>;
}

export function Checkbox({
  title,
  checked,
  disabled,
  onPress,
  style,
  description,
  error,
  semiChecked,
  extraData,
  checkboxStyle,
}: CheckboxProps) {
  const {theme} = useTheme();
  const handlePress = () => onPress?.();
  const textDisabled = theme.text.neutral[disabled ? 'disabled' : 'lighter'];

  return (
    <Pressable
      disabled={disabled}
      onPress={handlePress}
      style={[styles.checkContainer, style]}
      accessible
      accessibilityRole="checkbox"
      accessibilityState={{checked, disabled}}
      accessibilityLabel={title}>
      <Check
        checked={checked}
        disabled={disabled}
        error={error}
        semiChecked={semiChecked}
        onPress={onPress}
        style={checkboxStyle}
      />
      <View style={styles.titleContainer}>
        {!!title && (
          <Typography
            color={
              disabled
                ? theme.text.neutral.disabled
                : error
                ? theme.text.feedback.error
                : theme.text.neutral.default
            }>
            {title}
          </Typography>
        )}
        {!!description && (
          <Typography variant="xs" color={textDisabled}>
            {description}
          </Typography>
        )}
      </View>
      {!!extraData && (
        <Typography variant="xs" color={textDisabled}>
          {extraData}
        </Typography>
      )}
    </Pressable>
  );
}

type CheckboxControllerProps = Omit<
  CheckboxProps,
  'checked' | 'error' | 'onPress'
> &
  UseInputControllerProps;

export function CheckboxController({
  name,
  showSuccess,
  ...props
}: CheckboxControllerProps) {
  const {isError, onChange, value} = useInputController({
    name,
    showSuccess,
  });

  const onPress = () => onChange?.(!value);

  return (
    <Checkbox {...props} checked={value} error={isError} onPress={onPress} />
  );
}

export * from './components/Check';
