import React, { useEffect, useState } from 'react';
import { StyleSheet, View } from 'react-native';
import Dropdown from '../../components/Dropdown';
import apiVoucher from '../../api/apiVoucher';
import TextView from '../../components/TextView';

export default VoucherType = ({
  type="",
  onChange
}) => {
  const [options, setOption] = useState([])
  const [label, setLabel] = useState([])
  useEffect(() => {
    apiVoucher.getVoucherTypeOptions().then(res => {
      if (res.data) {
        const opt = [];
        const names = $t("voucher.typeOptions")
        res.data.forEach(item => {
          opt.push({
            label: names[item.key],
            value: item.value
          })
        });
        setOption(opt);
        setLabel(opt[0].label);
      }
    }).catch(err => {
      setOption([])
    })
  },[])
  return (
    <View style={styles.typeView}>
      <View style={ui.flex1}></View>
      <TextView style={styles.typeText}>{label}</TextView>
      { options.length > 0 &&
      <Dropdown
        style={styles.selectView}
        textStyle={styles.selectText}
        rippleStyle={{}}
        title={$t('voucher.voucherType')}
        prefixText="+"
        list={options}
        value={type}
        nameKey='label'
        valueKey='value'
        onChange={(value, index)=> {
          setLabel(options[index].label)
          onChange(value)
        }}/>
      }
    </View>
  )
};

const styles = StyleSheet.create({
  typeView: {
    marginRight: -8,
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  selectView: {
    flex: 1,
    marginTop: 8,
    paddingRight: 8,
    alignItems: 'center',
    flexDirection: 'row'
  },
  selectText: {
    color: textPrimary,
    fontSize: 14,
    padding: 8,
    opacity: 0
  },
  typeText: {
    top: 8,
    bottom: 0,
    color: textPrimary,
    right: 35,
    fontSize: 14,
    position: 'absolute'
  }
})