import React, {useEffect, useState} from 'react';
import {Platform, StyleSheet, Text, TextInput, View} from 'react-native';
import HeaderBack from '../../components/Header/HeaderBack';

import PickerItem from '../../components/Picker/PickerItem';
import I18n from '../../helper/i18/i18n';
import AppText from '../../components/AppText';
import {
  floatToPriceVnd,
  getFontXD,
  HEIGHTXD,
  toPriceVnd,
  WIDTHXD,
} from '../../Config/Functions';
import R from '../../assets/R';
import {getUnitList} from '../../apis/Functions/Transaction';
import {showAlert, TYPE} from '../../components/DropdownAlert';
import {hideLoading, showLoading} from '../../actions/loadingAction';
import {connect} from 'react-redux';

const ConvertUnit = (props) => {
  const [fromUnitList, setFromUnitList] = useState([]);
  const [toUnitList, setToUnitList] = useState([]);
  const [toUnit, setToUnit] = useState();
  const [fromUnit, setFromUnit] = useState();
  const [number, setNumber] = useState(null);
  const [rateItem, setRateItem] = useState({
    value_one: 0.025000000373,
    value_two: 0,
    name: 'Kg,',
  });
  const [result, setResult] = useState();
  useEffect(() => {
    getDataUnit();
  }, []);

  useEffect(() => {
    calcultorResult();
  }, [number, fromUnit, toUnit]);

  const getDataUnit = async () => {
    props.showLoading();
    const res = await getUnitList({
      platform: Platform.OS,
    });
    if (res.status == 200 && res.data.code == 200) {
      setFromUnitList(res.data.data);
      setFromUnit(res.data.data[0]);
      onChangeFromUnit('', res.data.data[0]);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
    }
    props.hideLoading();
  };

  const onChangeNumber = (string) => {
    let number = string.toString().split(',').join('');
    setNumber(number);
  };

  const onChangeFromUnit = (value, item) => {
    setFromUnit(item);
    let toUnit = [];
    item.rates.map((rateItem) => {
      toUnit.push({
        id: rateItem.to_unit_id,
        value: rateItem.to_unit.name,
        name: rateItem.to_unit.name,
        rate: rateItem.value_one > 0 ? rateItem.value_one : rateItem.value_two,
      });
    });
    setToUnitList(toUnit);
    setToUnit(toUnit[0]);
  };

  const onChangeToUnit = (value, item) => {
    setToUnit(item);
  };

  const calcultorResult = () => {
    if (number && number != '' && parseFloat(number) > 0) {
      let result = parseFloat(number) * toUnit.rate;
      setResult(
        `${floatToPriceVnd(number.toString())} ${
          fromUnit.name
        } = ${floatToPriceVnd(result.toString())} ${toUnit.name}`,
      );
    } else {
      setResult('');
    }
  };

  return (
    <View style={{flex: 1}}>
      <HeaderBack title={'ConvertUnit'} />
      <View style={{flex: 1, paddingTop: 20, paddingHorizontal: 20}}>
        <AppText style={styles.txtTitle} i18nKey={'Count'} />
        <View style={styles.Item}>
          <View style={styles.wrap}>
            <TextInput
              onChangeText={(val) => onChangeNumber(val)}
              keyboardType={'number-pad'}
              style={styles.wrapInput}
              maxLength={12}
              value={floatToPriceVnd(number)}
            />
          </View>
        </View>

        <View style={styles.Item}>
          <View style={styles.wrap}>
            <PickerItem
              width={WIDTHXD(480)}
              data={fromUnitList}
              defaultValue={fromUnit?.name}
              value={fromUnit?.name}
              onValueChange={(value, item) => {
                onChangeFromUnit(value, item);
              }}
            />
            {/*<TouchableOpacity>*/}
            {/*  <Icon name={'exchange'} size={30} color={R.colors.black} />*/}
            {/*</TouchableOpacity>*/}

            <PickerItem
              width={WIDTHXD(480)}
              data={toUnitList}
              defaultValue={toUnit?.name}
              value={toUnit?.name}
              onValueChange={(value, item) => {
                onChangeToUnit(value, item);
              }}
            />
          </View>
        </View>

        <Text style={styles.txtResult}>{result}</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  txtTitle: {
    fontSize: getFontXD(42),
    color: R.colors.color777,
    marginBottom: 5,
  },
  note: {
    fontSize: getFontXD(36),
    fontStyle: 'italic',
    marginTop: 10,
  },
  row: {
    height: HEIGHTXD(109),
    width: '80%',
    justifyContent: 'space-between',
    marginVertical: 5,
    paddingHorizontal: 10,
  },
  footer: {
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 40,
  },
  btnContainer: {
    width: WIDTHXD(428),
    height: HEIGHTXD(120),
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: R.colors.main,
    borderRadius: 10,
  },
  txtBtn: {
    fontSize: getFontXD(48),
    color: R.colors.white,
    fontWeight: '600',
  },
  wrapInput: {
    width: '100%',
    backgroundColor: R.colors.white,
    height: HEIGHTXD(109),
    fontSize: getFontXD(42),
    borderRadius: 5,
    paddingHorizontal: 10,
    paddingVertical: 0,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,
    elevation: 2,
    color: R.colors.black,
  },
  wrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  Item: {
    marginBottom: 20,
  },
  txtNote: {
    fontSize: getFontXD(36),
    textAlign: 'right',
    marginTop: 10,
  },
  txtResult: {
    fontSize: getFontXD(52),
    color: R.colors.black,
    fontWeight: '600',
    textAlign: 'center',
    marginTop: 20,
  },
});
const mapStateToProps = (state) => {
  return {};
};
export default connect(mapStateToProps, {
  showLoading,
  hideLoading,
})(ConvertUnit);
