import React, { useEffect, useRef, useState } from 'react';
import { FlatList, Keyboard, Pressable, StyleSheet, Text, View } from 'react-native';
import Modal from 'react-native-modal';
import Button from './Button';
import Dialog, { getDialogWidth } from './Dialog';

//const DialogMaxWidth = $vw(85) > 500 ? 500 : $vw(85);
//const DialogIOSWidth = $vw(75) > 450 ? 450 : $vw(75);

export default Dropdown = ({
    list = [],
    title = '',
    value,
    onChange,
    nameKey,
    valueKey,
    prefixText='',//前缀
    suffixText='',//后缀
    itemHeight=50,
    prefixList='',//列表前缀
    suffixList='',//列表后缀
    rippleStyle=ripple,
    style = styles.valueView,
    textStyle = styles.valueText,
    placeholderStyle=styles.placeText,
    placeholder='',
    showText = true,
    showIcon = true,
    iconColor = '#888',
    iconStyle = styles.iconStyle,
    autoSelect = true,
    customerItemView
  }) => {
  
  const refFlat = useRef();
  const [visible, showDialog] = useState(false);
  const [selected, changeValue] = useState('');
  const [currentIndex, setCurrent] = useState(0);
  
  useEffect(() => {
    if (value !== selected) {
      changeItem();
    }
  }, [value, []]);

  useEffect(() => {
    if (autoSelect && list.length > 0) {
      if (value == undefined) {
        const item = list[0];
        /*if (nameKey) {
          changeValue(item[nameKey]);
        } else {
          changeValue(item);
        }*/
        setChange(valueKey ? item[valueKey] : item, 0);
      } else {
        changeItem(true);
      }
    }
  }, [list]);

  const changeItem = (init) => {
    if (nameKey && valueKey) {
      for (var i = 0; i < list.length; i++) {
        let item = list[i];
        if (item[valueKey] == value) {
          changeValue(prefixText+item[nameKey]+suffixText);
          if (list.length > 20) {
            setCurrent(i > 5 ? i - 4 : 0);
          }
          return;
        }
      }
      if (init) {
        const item = list[0];
        setChange(item[valueKey], 0);
      }
    } else {
      if (init) {
        let _i = list.indexOf(value);
        if (_i >= 0) {
          setChange(list[_i], _i);
        } else {
          setChange(list[0], 0);
        }
      } else {
        changeValue(prefixText+value+suffixText);
      }
    }
  }
  const showList = () => {
    Keyboard.dismiss();
    showDialog(true);
    /*if (currentIndex > 0) {
      console.log(refFlat.current);
      setTimeout(() => {
        if (refFlat.current) {
          refFlat.current.scrollToIndex({
            animated: false,
            index: currentIndex,
            viewPosition: 0.5
          })
        }
      }, 100)
    }*/
  }
  const renderItem = ({ item, index, separators }) => {
    const _value = (valueKey ? item[valueKey] : item);
    if (customerItemView) {
      return customerItemView(item, index, () => {
        showDialog(false);
        setChange(_value, index);
      })
    } else {
      return (
        <Button
          text={prefixList + (nameKey ? item[nameKey] : item) + suffixList}
          style={styles.itemView}
          textStyle={styles.itemText}
          onClick={() => {
            showDialog(false);
            setChange(_value, index);
          }}
          iconRight={(_value == value) && <MaterialIcons name="radio-button-checked" color={colorAccent} size={22}/>}
        />
      )
    }
  }
  const setChange = (v, i) => {
    setTimeout(() => {
      if (onChange) {
        onChange(v, i)
      }
    }, 300);
    
  }
  return (
    <>
      <Pressable
        style={({pressed }) => [
          pressed && isIOS && {
            backgroundColor: rippleColor
          },
          style
        ]}
        android_ripple={rippleStyle}
        onPress={() => showList()}>
        { showText && 
          ( selected 
            ? <Text style={[ui.flex1, textStyle]} numberOfLines={1}>{selected}</Text>
            : <Text style={[textStyle, placeholderStyle]} numberOfLines={1}>{placeholder}</Text>
          )
        }
        { showIcon && 
          <Entypo 
            name={'chevron-thin-down'}
            size={14}
            color={iconColor}
            style={iconStyle}
          />
        }
      </Pressable>
      <Modal
        isVisible={visible}
        onTouchOutside={() => showDialog(false)}
        onBackdropPress={() => showDialog(false)}
        onBackButtonPress={() => showDialog(false)}
        {...Dialog.modalProps}
      >
        <View style={styles.dialog}>
          { title !== '' && <Text style={styles.title}>{title}</Text> }
          <FlatList
            data={list}
            ref={refFlat}
            renderItem={renderItem}
            initialScrollIndex={currentIndex}
            keyExtractor={(item, index) => index}
            style={{maxHeight: $vh(55)}}
            getItemLayout={(data, index) => (
              {length: itemHeight, offset: itemHeight * index, index}
            )}
          />
        </View>
      </Modal>
    </>
  );
}

const styles = StyleSheet.create({
  dialog: {
    width: getDialogWidth(),
    marginLeft: 'auto',
    marginRight: 'auto',
    paddingTop: isIOS ? 12 : 8,
    paddingBottom: isIOS ? 12 : 8,
    backgroundColor: colorLight,
    borderRadius: isIOS ? 10 : 3
  },
  title: {
    color: '#000',
    paddingTop: 8,
    paddingLeft: 16,
    paddingBottom: 16,
    fontSize: 17,
    fontWeight: 'bold'
  },
  valueView: {
    paddingLeft: 16,
    paddingRight: 32,
    alignItems: 'center',
    flexDirection: 'row'
  },
  valueText: {
    color: textPrimary,
    fontSize: 16
  },
  itemView: {
    borderRadius: 0,
    backgroundColor: colorLight
  },
  itemText: {
    flex: 1,
    color: textPrimary,
    fontSize: 14,
    textAlign: 'left',
    fontWeight: 'normal'
  },
  placeText: {
    flex: 1,
    color: textPlacehoder
  },
  iconStyle: {
    top: '50%',
    right: 16,
    marginTop: -7,
    position: 'absolute',
  }
});
