import * as React from 'react';
import type { ViewProps } from 'react-native';
import { TextInput, View } from 'react-native';
import { useRestyle, createVariant, createBox } from '@shopify/restyle';
import { Normalize } from '../../utils/normalize';
import { Theme, colors, fonts } from '../../theme/theme';
import { Text } from '../Text';
import { Box } from '../Box';

type TextInputProps = React.ComponentPropsWithRef<typeof TextInput> & {
  label?: string;
  icon?: React.ReactNode;
  error?: boolean;
  textHelper?: string;
  disabled?: boolean;
  width?: string | number;
};

const variant = createVariant<Theme>({
  themeKey: 'fonts',
  defaults: {
    flex: 1,
    paddingLeft: 'spacing-s',
    fontFamily: fonts.caustenRoundRegular,
    fontSize: Normalize(16),
    paddingBottom: 'spacing-xxxs',
  },
});

const ViewComponent = createBox<
  Theme,
  ViewProps & { children?: React.ReactNode }
>(View);
const restyleFunctions = [variant];

export const TextFieldUnderline = React.forwardRef<TextInput, TextInputProps>(
  ({ width, ...rest }, ref) => {
    const props: any = useRestyle(restyleFunctions as any, rest);
    const [focus, setFocus] = React.useState(false);
    const inputBorderColor = focus || rest?.value ? 'gray200' : 'gray60';
    const TextInputStyles = {
      color: rest.disabled ? colors.gray100 : colors.yankeesBlue,
      fontFamily: 'CaustenRound-Regular',
      paddingLeft: 0,
    };
    return (
      <ViewComponent width={width || '100%'}>
        <Text
          fontSize={12}
          color={rest?.disabled ? 'gray100' : 'gray300'}
          mb="spacing-xxxxs"
        >
          {rest.label}
        </Text>
        <Box
          flexDirection={'row'}
          backgroundColor={'white'}
          paddingVertical={'spacing-xxxs'}
          width={'100%'}
          borderBottomWidth={rest?.disabled ? 0 : 1}
          borderBottomColor={rest.error ? 'chiperBrandRed' : inputBorderColor}
        >
          <TextInput
            {...props}
            style={[...props.style, { ...TextInputStyles }]}
            ref={ref}
            clearButtonMode="while-editing"
            placeholderTextColor={colors.gray200}
            editable={!rest.disabled}
            onFocus={() => setFocus(true)}
            onBlur={() => setFocus(false)}
            placeholder={rest.placeholder || ''}
          />
        </Box>
        {rest.textHelper && (
          <Text
            fontSize={12}
            marginTop={'spacing-xxs'}
            color={rest.error ? 'chiperBrandRed' : 'gray200'}
          >
            {rest.textHelper}
          </Text>
        )}
      </ViewComponent>
    );
  }
);
