// @flow
import React, { useState } from 'react';
import _ from 'lodash';
import {
  Text, TouchableOpacity, View, TouchableWithoutFeedback,
} from 'react-native';
import Modal from 'react-native-modal';
import ListItem from '../../pages/Agera-App-Insure/components/ListItem';
import { SinglePicker } from '../Agera-App-Base-Pickers';

const time = 315;

export default function Picker(props) {
  const {
    text, value, picker, beforeValue, afterValue,
  } = props;
  const data = ['测试1', '测试2', '测试3', '测试4', '测试5'];
  const [isShow, setIsShow] = useState(false);
  const [showValue, setShowValue] = useState(value || '请选择');
  let CustomPickerRef = null;
  const PickerView = picker || SinglePicker;
  return (
    <View>
      <ListItem
        style={[{
          marginTop: 10,
          borderBottomColor: '#ccc',
        }, props.style]}
        text={text}
      >
        <TouchableOpacity
          onPress={() => {
            setIsShow(true);
            setTimeout(() => {
              if (CustomPickerRef) {
                CustomPickerRef.show();
              }
            });
          }}
        >
          <View style={{ flexDirection: 'row', alignItems: 'stretch' }}>
            {beforeValue}
            <Text style={{ color:'#999', fontSize: 14}}>{showValue}</Text>
            {afterValue}
          </View>
        </TouchableOpacity>
      </ListItem>
      <Modal
        style={{
          justifyContent: 'flex-end',
          margin: 0,
          padding: 0,
        }}
        isVisible={isShow}
        animationIn="slideInUp"
        animationOut="slideOutDown"
        animationOutTiming={time}
        animationInTiming={time}
        backdropTransitionInTiming={time}
        backdropTransitionOutTiming={time}
        onModalHide={() => setIsShow(false)}
      >
        <TouchableWithoutFeedback
          onPress={() => {
            setIsShow(false);
          }}
        >
          <View style={{ flex: 1, backgroundColor: 'rgb(0,0,0,0.5)' }} />
        </TouchableWithoutFeedback>
        <PickerView
          ref={(ref) => {
            CustomPickerRef = ref;
          }}
          list={data}
          title={text}
          onCancel={() => {
            setIsShow(false);
          }}
          onConfirm={(index) => {
            setIsShow(false);
            console.log('PickerView', index);
            if (_.isNumber(index)) {
              setShowValue(data[index]);
            } else if (_.isArray(index)) {
              setShowValue(index.toString().replace(/,/g, ''));
            }
          }}
        />
      </Modal>
    </View>
  );
}
