import React, { useCallback, useState } from 'react';
import {
  ViewStyle,
  View,
  TextInput,
  TouchableOpacity,
  ImageStyle,
  Image,
  StyleSheet,
} from 'react-native';
import {
  useCustomFontStyle,
  useGifPicker,
  useStyles,
  useTheme,
} from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';

export type LLGifPickerHeaderStyles = {
  headerContainer: ViewStyle;
  searchInput: ViewStyle;
  closeIcon: ImageStyle;
};

export type LLGifPickerHeaderProps =
  ComponentStyleProp<LLGifPickerHeaderStyles> & {
    onSearchInputChange: ReturnType<
      typeof useGifPicker
    >['onGifSearchInputChange'];
    closeGifPicker: () => void;
  };

export function LLGifPickerHeader({
  onSearchInputChange,
  closeGifPicker,
  styles: stylesProp,
}: LLGifPickerHeaderProps) {
  const [gifSearchInput, setGifSearchInput] = useState('');
  const { theme, themeAssets } = useTheme();
  const gifPickerHeaderStyles = useStyles({
    componentStylesFn: getLLGifPickerHeaderStyles,
    stylesProp,
  });
  const searchInputStyle = useCustomFontStyle({
    style: gifPickerHeaderStyles.searchInput,
  });
  const onSearchInputHandler = useCallback(
    (inputValue) => {
      setGifSearchInput(inputValue);
      onSearchInputChange(inputValue);
    },
    [onSearchInputChange]
  );

  return (
    <View style={gifPickerHeaderStyles.headerContainer}>
      <TextInput
        placeholder="Search Giphy"
        value={gifSearchInput}
        style={searchInputStyle}
        placeholderTextColor={theme.secondaryText}
        onChangeText={onSearchInputHandler}
      />
      <TouchableOpacity
        onPress={closeGifPicker}
        accessibilityLabel="Close Gif picker"
      >
        <Image
          style={gifPickerHeaderStyles.closeIcon}
          source={themeAssets.close}
        />
      </TouchableOpacity>
    </View>
  );
}

const getLLGifPickerHeaderStyles: LLComponentStyleFn<
  LLGifPickerHeaderStyles
> = ({ theme }) =>
  StyleSheet.create({
    headerContainer: {
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: 15,
      paddingTop: 15,
    },
    searchInput: {
      borderRadius: 10,
      height: 45,
      paddingVertical: 5,
      paddingHorizontal: 12,
      flex: 1,
      color: theme.text,
      backgroundColor: theme.background,
    },
    closeIcon: {
      width: 30,
      height: 30,
      marginLeft: 10,
    },
  });
