import React, {useRef, useState} from 'react';
import {View, TextInput, TouchableOpacity, Image, Text} from 'react-native';
import Chip from './chip';
import {BACKSPACE, DELIMITERS} from '../../config/constants';
import {isValidEmail} from '../../config/Functions';
import R from '../../assets/R';

export const EmailChipInput = ({
  title,
  entries,
  onSubmit,
  chipImage,
  autoCorrect,
  TextInputProps,
  containerStyle,
  chipContainerStyle,
  inputContainerStyle,
  inputStyle,
  placeholderTextColor,
  chipTextStyle,
  delimiters = DELIMITERS,
  keyboardAppearance = 'default',
  clearButtonMode = 'while-editing',
  placeholder,
  autoCapitalize = 'none',
  autoFocus = false,
  keyboardType = 'email-address',
  widthContainerInput = '100%',
}) => {
  const ref = useRef(null);
  const [emails, setEmails] = useState(entries);
  const [value, setValue] = useState('');
  const [isExpanded, setIsExpanded] = useState(false);
  const [showInput, setShowInput] = useState(true); // mở sẵn

  // Thu gọn chỉ khi blur & không có giá trị
  const onBlur = () => {
    if (!value) setShowInput(false);
  };

  // Chip -> chuyển sang edit
  const handleOnPressChip = index => {
    setValue(emails[index]);
    setEmails(emails.filter((_, i) => i !== index));
    setShowInput(true); // remount TextInput -> autoFocus
  };

  const lastEntry = emails[emails.length - 1];

  // Nhập text + thêm qua delimiter
  const onTextChange = inputValue => {
    if (inputValue === lastEntry) return setValue('');

    if (
      isValidEmail(inputValue) &&
      delimiters.some(d => inputValue.endsWith(d))
    ) {
      const cleaned = inputValue.slice(0, -1).trim();
      if (cleaned) {
        const newEntries = [...emails, cleaned];
        setEmails(newEntries);
        setValue('');
        onSubmit?.(newEntries);
        setShowInput(true); // remount vẫn giữ mở
      } else {
        setValue('');
      }
      return;
    }

    setValue(inputValue);
  };

  // Backspace khi trống -> edit chip cuối
  const onKeyPress = ({nativeEvent: {key}}) => {
    if (!value && key === BACKSPACE && lastEntry) {
      setValue(lastEntry);
      setEmails(emails.filter(e => e !== lastEntry));
      setShowInput(true); // remount -> autoFocus
    }
  };

  // Submit bằng Enter nhưng KHÔNG đóng input
  const submitCurrent = () => {
    const v = value.trim();
    if (!isValidEmail(v)) return;
    const newEntries = [...emails, v];
    setEmails(newEntries);
    setValue('');
    onSubmit?.(newEntries);
    setShowInput(true); // vẫn mở để nhập tiếp
  };

  const toggleExpanded = () => setIsExpanded(!isExpanded);

  const renderChips = () => {
    if (emails.length === 0) return null;

    if (emails.length === 1 || isExpanded) {
      return emails.map((email, index) => (
        <Chip
          index={index}
          value={email}
          onPress={handleOnPressChip}
          key={index}
          chipContainerStyle={chipContainerStyle}
          chipImage={chipImage}
          chipTextStyle={chipTextStyle}
          marginHorizontal={5}
        />
      ));
    }

    return (
      <>
        <Chip
          index={0}
          value={emails[0]}
          onPress={handleOnPressChip}
          key={0}
          chipContainerStyle={chipContainerStyle}
          chipImage={chipImage}
          chipTextStyle={chipTextStyle}
          
        />
        <Text
          style={{
            fontSize: 12,
            color: R.colors.gray,
            fontFamily: R.fonts.fontMedium,
            alignSelf: 'center',
          }}>
         +{emails.length - 1}
        </Text>
      </>
    );
  };

  // Khi input ẩn: dùng TouchableOpacity để mở.
  // Khi input hiện: dùng View + pointerEvents để không chặn touch của chip/nút X.
  const Wrapper = showInput ? View : TouchableOpacity;
  const wrapperProps = showInput
    ? {pointerEvents: 'box-none'}
    : {
      onPress: () => setShowInput(true), 
      activeOpacity: 0.7,
      hitSlop: { top: 8, bottom: 8, left: 8, right: 8 },
    };

  return (
    <View style={containerStyle}>
      <View
        style={{
          flexDirection: 'row',
          // flexWrap: emails.length > 0 ? 'wrap' : 'nowrap',
          alignItems: 'center',
        }}>
        <Wrapper
          {...wrapperProps}
          style={{
            minHeight: 35,
            flexDirection: 'row',
            flexWrap: emails.length > 0 ? 'wrap' : 'nowrap',
            alignItems: 'center',
            flex:1,
          }}>
          <Text
            style={{
              fontSize: 12,
              color: R.colors.black,
              fontFamily: R.fonts.fontMedium,
              fontWeight: '600',
            }}>
            {title}
          </Text>
          {renderChips()}
          {showInput && (
          <View
            style={[
              { height: 35, widthContainerInput,},
              inputContainerStyle,
            ]}>
            <TextInput
              ref={ref}
              value={value}
              onChangeText={onTextChange}
              onKeyPress={onKeyPress}
              onSubmitEditing={submitCurrent}   // nhập liên tiếp
              onBlur={onBlur}                   // chỉ đóng khi rỗng
              blurOnSubmit={false}              // Enter không blur
              keyboardType={keyboardType}
              clearButtonMode={clearButtonMode}
              autoCorrect={autoCorrect}
              autoFocus={showInput || autoFocus} // <-- tự focus khi mount
              placeholder={placeholder}
              autoCapitalize={autoCapitalize}
              keyboardAppearance={keyboardAppearance}
              placeholderTextColor={placeholderTextColor}
              style={[
                {
                  fontSize: 12,
                  color: R.colors.black,
                  fontFamily: R.fonts.fontMedium,
                  fontWeight: '600',
                  padding: 0,
                  height: 35,
                  marginHorizontal:3,
                  textAlignVertical: 'center',
                },
                inputStyle,
              ]}
              {...TextInputProps}
            />
          </View>
        )}
        </Wrapper>

        {emails.length > 1 && (
          <View style={{position: 'absolute', right: -3, top: 5}}>
            <TouchableOpacity
              onPress={toggleExpanded}
              style={{
                backgroundColor: R.colors.blue4,
                borderRadius: 15,
                padding: 3,
              }}>
              <Image
                source={isExpanded ? R.images.icBack2 : R.images.icDrop}
                style={{width: 20, height: 20, tintColor: R.colors.black}}
              />
            </TouchableOpacity>
          </View>
        )}

      </View>
    </View>
  );
};

export default React.memo(EmailChipInput);
