import React, {useEffect, useState} from 'react';
import {Alert, Platform} from 'react-native';
import {connect} from 'react-redux';
import {getTransaction} from '../../apis/Functions/users';
import {getImagesHome} from '../../apis/Functions/General';
import {getPriceTable} from '../../apis/Functions/Home';
import I18n from '../../helper/i18/i18n';

import HomeView from './HomeView';
import {getListCategoryProduct} from '../../apis/Functions/Transaction';
import {hideLoading, showLoading} from '../../actions/loadingAction';
import _ from 'lodash';
import {showAlert, TYPE} from '../../components/DropdownAlert/index';

const Home = (props) => {
  const [data, setData] = useState({total_deposit: 0, total_withdraw: 0});
  const [dataPrice, setDataPrice] = useState([]);
  const [dataPriceFilter, setDataPriceFilter] = useState([]);
  const [listImage, setListImage] = useState([]);
  const [filters, setFilters] = useState([]);
  const [filterId, setFilterId] = useState(null);
  const [isSortName, setIsSortName] = useState(null);
  const [isSortPercent, setIsSortPercent] = useState(null);
  const [isSortPriceOpenClose, setIsSortPriceOpenClose] = useState(null);
  const [isSortPriceHighLow, setIsSortPriceHighLow] = useState(null);
  const SORT_TYPE = {
    DESC: 'DESC',
    ASC: 'ASC',
  };
  useEffect(() => {
    getData();
    initSocket();
  }, []);
  useEffect(() => {
    const newList =
      filterId == -1
        ? [...dataPrice]
        : _.filter([...dataPrice], (item) => item.category_id == filterId);
    setDataPriceFilter(newList);
  }, [dataPrice]);

  const initSocket = () => {
    let io = require('socket.io-client');
    let socket = io.connect('http://222.252.22.174:8087', {
      transports: ['websocket'],
      jsonp: false,
      reconnect: true,
    });
    socket.on('response-update-price', (message) => {
      receivedMessage(message);
    });
  };

  const receivedMessage = (message) => {
    setDataPrice(message);
  };

  const getData = async () => {
    props.showLoading();
    const res = await getTransaction({});
    if (res.data.code == 200 && res.data.data) {
      setData(res.data.data);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
    }

    const res1 = await getImagesHome({});
    if (res1.data.code == 200 && res1.data.data) {
      setListImage(res1.data.data);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
    }
    const resCategoryProduct = await getListCategoryProduct({
      keyword: '',
      platform: Platform.OS,
      page_size: 20,
      page_index: 1,
      type: 'PRODUCT',
    });
    console.log(resCategoryProduct);
    if ((resCategoryProduct.data.code = 200 && resCategoryProduct.data.data)) {
      let data = [];
      data.push({id: -1, name: 'All'});
      setFilters(data.concat([...resCategoryProduct.data.data]));
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
    }
    const resPriceHome = await getPriceTable({});
    if (resPriceHome.data.code == 200 && resPriceHome.data.data) {
      setDataPrice(resPriceHome.data.data);
      setDataPriceFilter(resPriceHome.data.data);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
    }
    props.hideLoading();
    console.log('filterId', filterId);
  };

  const changeFilter = (id) => {
    setFilterId(id);
    const newList =
      id == -1
        ? [...dataPrice]
        : _.filter([...dataPrice], (item) => item.category_id == id);
    setDataPriceFilter(newList);
    console.log(id, newList);
  };

  const onSortByName = () => {
    let type = 'ASC';
    if (!isSortName || isSortName == SORT_TYPE.ASC) type = SORT_TYPE.DESC;
    let newData =
      type == SORT_TYPE.ASC
        ? [...dataPriceFilter].sort((a, b) => (a.name > b.name ? 1 : -1))
        : [...dataPriceFilter].sort((a, b) => (a.name < b.name ? 1 : -1));
    setDataPriceFilter(newData);
    setIsSortPriceOpenClose(null);
    setIsSortName(type);
    setIsSortPercent(null);
    setIsSortPriceHighLow(null);
  };
  const onSortByPercent = () => {
    let type = 'ASC';
    if (!isSortPercent || isSortPercent == SORT_TYPE.ASC) type = SORT_TYPE.DESC;
    let newData =
      type == SORT_TYPE.ASC
        ? [...dataPriceFilter].sort((a, b) => (a.change > b.change ? 1 : -1))
        : [...dataPriceFilter].sort((a, b) => (a.change < b.change ? 1 : -1));
    setDataPriceFilter(newData);
    setIsSortPriceOpenClose(null);
    setIsSortName(null);
    setIsSortPercent(type);
    setIsSortPriceHighLow(null);
  };
  const onSortByPriceOpenClose = () => {
    let type = 'ASC';
    if (!isSortPriceOpenClose || isSortPriceOpenClose == SORT_TYPE.ASC)
      type = SORT_TYPE.DESC;
    let newData =
      type == SORT_TYPE.ASC
        ? [...dataPriceFilter].sort((a, b) =>
            a.open_price > b.open_price ? 1 : -1,
          )
        : [...dataPriceFilter].sort((a, b) =>
            a.open_price < b.open_price ? 1 : -1,
          );
    setDataPriceFilter(newData);
    setIsSortPriceOpenClose(type);
    setIsSortName(null);
    setIsSortPercent(null);
    setIsSortPriceHighLow(null);
  };
  const onSortByPriceHighLow = () => {
    let type = 'ASC';
    if (!isSortPriceHighLow || isSortPriceHighLow == SORT_TYPE.ASC)
      type = SORT_TYPE.DESC;
    let newData =
      type == SORT_TYPE.ASC
        ? [...dataPriceFilter].sort((a, b) =>
            a.high_price > b.high_price ? 1 : -1,
          )
        : [...dataPriceFilter].sort((a, b) =>
            a.high_price < b.high_price ? 1 : -1,
          );
    setDataPriceFilter(newData);
    setIsSortPriceOpenClose(null);
    setIsSortName(null);
    setIsSortPercent(null);
    setIsSortPriceHighLow(type);
  };

  return (
    <HomeView
      data={data}
      dataPrice={dataPriceFilter}
      listImage={listImage}
      filterId={filterId}
      filters={filters}
      setFilterId={changeFilter}
      onSortByName={onSortByName}
      onSortByPercent={onSortByPercent}
      onSortByPriceOpenClose={onSortByPriceOpenClose}
      onSortByPriceHighLow={onSortByPriceHighLow}
    />
  );
};

const mapStateToProps = (state) => {
  return {
    user: state.userReducer,
  };
};
export default connect(mapStateToProps, {showLoading, hideLoading})(Home);
