import React, { forwardRef } from 'react';
import { View, ViewStyle } from 'react-native';
import tw from '../lib/tailwind';
import { theme } from '../theme';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import MyTextInput from './textinput';
import MyTouchableOpacity from './touchable-opacity';

interface SearchBarProps {
  value: string;
  onChangeText: (text: string) => void;
  placeholder?: string;
  editable?: boolean;
  onSubmitEditing?: () => void;
  returnKeyType?: 'search' | 'done' | 'go' | 'next' | 'send';
  containerStyle?: ViewStyle;
  onPress?: () => void;
  activeOpacity?: number;
}

const SearchBar = forwardRef<any, SearchBarProps>(({
  value,
  onChangeText,
  placeholder = 'Search fresh meat...',
  editable = true,
  onSubmitEditing,
  returnKeyType = 'search',
  containerStyle,
  onPress,
  activeOpacity = 0.8,
}, ref) => {
  const Wrapper = onPress ? MyTouchableOpacity : View;

  const wrapperProps = onPress ? {
    style: [tw`flex-row items-center bg-white rounded-2xl px-4 h-12 mb-6 shadow-md`, { overflow: 'visible' }, containerStyle],
    onPress,
    activeOpacity,
  } : {
    style: [tw`flex-row items-center bg-white rounded-2xl px-4 h-12 mb-6 shadow-md`, { overflow: 'visible' }, containerStyle],
  };

  return (
    <Wrapper {...wrapperProps}>
      <MaterialIcons name="search" size={24} color={theme.colors.brand500} />
      <MyTextInput
        ref={ref}
        style={[tw`flex-1 text-base text-gray-800 bg-transparent h-8`, { borderWidth: 0 }]}
        placeholder={placeholder}
        placeholderTextColor="#9CA3AF"
        value={value}
        onChangeText={onChangeText}
        editable={editable}
        onSubmitEditing={onSubmitEditing}
        returnKeyType={returnKeyType}
        onPress={onPress}
      />
    </Wrapper>
  );
});

SearchBar.displayName = 'SearchBar';

export default SearchBar;
