import React, {useState, useEffect} from 'react';
import {View, Text, StyleSheet, ScrollView, Alert} from 'react-native';
import HeaderBack from '../../../components/Header/HeaderBack';
import CheckBox from '@react-native-community/checkbox';
import R from '../../../assets/R';
import {getFontXD, toPriceVnd} from '../../../Config/Functions';
import ContainerTop from './ContainerTop';
import WrapNomarl from './WrapNomarl';
import Footer from './Footer';
import FeePro from './FeePro';
import {
  getListPacketCQG,
  openCQG,
  updateCQG,
} from '../../../apis/Functions/packetCQG';
import {connect} from 'react-redux';
import {showLoading, hideLoading} from '../../../actions/loadingAction';
import {useNavigation} from '@react-navigation/native';
import {saveUserToRedux} from '../../../actions/users';
import AppText from '../../../components/AppText';
import I18n from '../../../helper/i18/i18n';
import {showAlert, TYPE} from '../../../components/DropdownAlert/index';
const PacketCQG = (props) => {
  const [listData, setListData] = useState([]);
  const [fee, setFee] = useState({data: [], title: ''});
  const [feeConnect, setFeeConnect] = useState({data: [], title: ''});
  const [feeNonPro, setFeeNonPro] = useState({data: [], title: ''});
  const [feePro, setFeePro] = useState({data: [], title: ''});
  const [feeOperating, setOperrating] = useState({data: [], title: ''});
  const [totalMD, setTotalMD] = useState(0);
  const [totalTB, setTotalTB] = useState(0);
  const [isUpdate, setIsUpdate] = useState(false);
  const [listRegister, setListRegister] = useState([]);

  const navigate = useNavigation();

  const [price, setPrice] = useState(0);
  useEffect(() => {
    onChangeMoney();
  }, [listData]);

  useEffect(() => {
    getTotal();
  }, [feePro]);

  const getTotal = () => {
    let totalMD = 0;
    let totalTB = 0;
    if (feePro.data.length > 0)
      feePro.data.map((e) => {
        if (e.type_data == 'TB' && e.id != 11) totalTB += e.price_package.price;
        if (e.type_data == 'MD' && e.id != 10) totalMD += e.price_package.price;
      });
    setTotalMD(totalMD);
    setTotalTB(totalTB);
  };

  const onClick = async () => {
    const newList = listData.map((e) => e.id);
    let res;
    props.showLoading();
    if (isUpdate) {
      res = await updateCQG({packages: newList});
    } else {
      res = await openCQG({packages: newList});
    }

    props.hideLoading();
    if (res.data.code == 200) {
      props.saveUserToRedux(res.data.data);
      navigate.goBack();
      showAlert(TYPE.SUCCESS, I18n.t('Notification'), res.data.message);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
    }
  };

  const onChangeMoney = () => {
    setTimeout(() => {
      let totalMoney = 0;
      listData.map((e) => {
        if (e.id == 10) totalMoney -= totalMD;
        if (e.id == 11) totalMoney -= totalTB;
        totalMoney += e.price_package.price;
      });
      const result = listData.find((e) => e.id == 10);
      setPrice(totalMoney);
    }, 1000);
  };

  useEffect(() => {
    getData();
  }, []);

  const onChoosePacket = (item) => {
    if (listData.length != 0) setListData(listData.concat(item));
    else setListData([].concat(item));
    onChangeMoney();
  };

  const onChooseAllMD = (list) => {
    const newList = listData.concat(list);
    setListData(newList);
    onChangeMoney();
  };

  const onChooseAllTB = (list) => {
    const newList = listData.concat(list);
    setListData(newList);
    onChangeMoney();
  };

  const onRemoveAllMD = () => {
    const newList = listData.filter((e) => e.type_data != 'MD');
    setListData(newList);
    onChangeMoney();
  };

  const onRemoveAllTB = () => {
    const newList = listData.filter((e) => e.type_data != 'TB');
    setListData(newList);
    onChangeMoney();
  };
  const onRemovePacket = (item) => {
    const newList = listData.filter((e) => e.id != item.id);

    setListData(newList);
    onChangeMoney();
  };
  const getData = async () => {
    const res = await getListPacketCQG({});
    console.log(res);
    if ((res.data.code = 200 && res.data.data)) {
      if (res.data.data.fee) setFee(res.data.data.fee);
      if (res.data.data.fee_connect) setFeeConnect(res.data.data.fee_connect);
      if (res.data.data.fee_pro) setFeeNonPro(res.data.data.fee_pro);

      if (res.data.data.fee_non_pro) setFeePro(res.data.data.fee_non_pro);
      if (res.data.data.fee_operating)
        setOperrating(res.data.data.fee_operating);

      if (res.data.package_register.length > 0) {
        setListData(res.data.package_register);
        const temp = res.data.package_register.filter(
          (e) => e.id != 1 && e.id != 2,
        );
        const listId = temp.map((e) => e.id);
        setListRegister(listId);
        setIsUpdate(true);
      } else {
        setListData(res.data.data.fee.data);
      }
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
    }
  };

  return (
    <View style={{flex: 1}}>
      <HeaderBack title={'OpenAccountCQG'} />
      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={styles.container}>
          <AppText i18nKey={'Note_cqg'} />
          <ContainerTop fee={fee} />
          {feeOperating.data.length > 0 ? (
            <WrapNomarl
              onRemovePacket={onRemovePacket}
              onChoosePacket={onChoosePacket}
              data={feeOperating}
              listRegister={listRegister}
            />
          ) : null}
          {feeConnect.data.length > 0 ? (
            <WrapNomarl
              onRemovePacket={onRemovePacket}
              onChoosePacket={onChoosePacket}
              data={feeConnect}
              listRegister={listRegister}
            />
          ) : null}

          {feeNonPro.data.length > 0 ? (
            <WrapNomarl
              onRemovePacket={onRemovePacket}
              onChoosePacket={onChoosePacket}
              data={feeNonPro}
              listRegister={listRegister}
            />
          ) : null}

          <FeePro
            onRemovePacket={onRemovePacket}
            onChoosePacket={onChoosePacket}
            onChooseAllMD={onChooseAllMD}
            onChooseAllTB={onChooseAllTB}
            onRemoveAllMD={onRemoveAllMD}
            onRemoveAllTB={onRemoveAllTB}
            data={feePro}
            listRegister={listRegister}
          />

          <Footer onClick={onClick} price={price} />

          <View style={{height: 20}} />
        </View>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: 10,
    paddingTop: 10,
  },
  checkboxContainer: {
    flexDirection: 'row',
    marginBottom: 20,
  },
  checkbox: {
    alignSelf: 'flex-end',
  },
  txtNote: {
    fontStyle: 'italic',
  },
  wrap: {
    marginVertical: 10,
    backgroundColor: R.colors.white,
    paddingVertical: 10,
    paddingHorizontal: 10,
    borderRadius: 10,
    shadowColor: '#AFA9A9',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.25,
    shadowRadius: 1.84,
    elevation: 1,
  },
  item: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginVertical: 10,
  },
  txtMoney: {
    fontSize: getFontXD(42),
    color: '#FFB721',
  },
  txtTitle: {
    fontSize: getFontXD(42),
    color: R.colors.main,
    marginTop: 10,
    fontWeight: 'bold',
  },
  txtGroup: {
    fontSize: getFontXD(42),
    color: R.colors.main,
    fontStyle: 'italic',
  },
});

const mapStateToProps = (state) => {
  return {
    loadding: state.loadingReducer,
  };
};
export default connect(mapStateToProps, {
  showLoading,
  hideLoading,
  saveUserToRedux,
})(PacketCQG);
