import React, { forwardRef } from 'react';
import { useRestyle, createVariant } from '@shopify/restyle';
import { TextInput, TouchableOpacity } from 'react-native';
import { Box } from '../Box';
import CloseIcon from '../../icons/CloseIcon';
import { fonts, Theme } from './../../theme/theme';
import { Normalize } from '../../utils/normalize';
import { useTheme } from '../../theme/ThemeProvider';
import { MagnifyingGlass } from 'phosphor-react-native';

type TextInputProps = React.ComponentPropsWithRef<typeof TextInput> & {
  onChangeCancel: () => void;
};

const variant = createVariant<Theme>({
  themeKey: 'fonts',
  defaults: {
    flex: 1,
    paddingLeft: 'spacing-xs',
    fontFamily: fonts.caustenRoundRegular,
    color: 'darkBlueGray',
    fontSize: Normalize(16),
  },
});
const restyleFunctions = [variant];

export const TextFieldSearch = forwardRef<TextInput, TextInputProps>(
  ({ ...rest }, ref) => {
    const props = useRestyle(restyleFunctions as any, rest);
    const { colors } = useTheme();
    return (
      <Box
        flexDirection={'row'}
        justifyContent="center"
        alignItems={'center'}
        backgroundColor={'white'}
        height={Normalize(44)}
        width={'100%'}
        paddingHorizontal={'spacing-xs'}
        borderRadius={Normalize(4)}
        borderWidth={1}
        borderColor={'gray60'}
      >
        <Box paddingLeft={'spacing-xs'}>
          <MagnifyingGlass color={colors.yankeesBlue} size={Normalize(16)} />
        </Box>
        <TextInput
          placeholderTextColor={colors.darkBlueGray}
          ref={ref}
          {...props}
        />
        {rest.value ? (
          <Box paddingRight={'spacing-xs'}>
            <TouchableOpacity onPress={() => rest.onChangeCancel()}>
              <CloseIcon />
            </TouchableOpacity>
          </Box>
        ) : null}
      </Box>
    );
  }
);
