Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
8.3 kB
2
Indexable
Never
/* eslint-disable react-native/no-inline-styles */
import React, { useState, useMemo } from 'react';
import { nFormatter } from '../../../../utils/number_formatter';
import { View, Text, Colors } from 'react-native-ui-lib';
import { TouchableOpacity } from 'react-native';
import {
  VictoryAxis,
  VictoryBar,
  VictoryChart,
  VictoryLabel,
  VictoryTheme,
} from 'victory-native';
import colors from '../../../rb-constants/colors';

type Props = {
  report: any;
  socialMediaType: string;
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const Location = ({ report, socialMediaType }: Props) => {
  const memoized: any = useMemo(() => {
    const getTotal = (list: any) => {
      let total = 0;
      for (let i = 0; i < list.length; i += 1) {
        total += list[i].value;
      }
      return total;
    };

    const getCountriesData = (location: any) => {
      const countriesData = [['Countries', '%']];
      const total = getTotal(location.countries);
      const len = dataLimit(location.countries);

      for (let i = 0; i < len; i += 1) {
        const countryData = countriesData.find(
          item => item[0] === location.countries[i].name,
        );
        if (!countryData) {
          countriesData.push([
            location.countries[i].name,
            (location.countries[i].value * 100) / total,
          ]);
        }
      }

      return countriesData;
    };

    const getCitiesData = (location: any) => {
      const citiesData = [['Cities', '%']];
      const len = dataLimit(location.cities);
      const total = getTotal(location.cities);

      for (let i = 0; i < len; i += 1) {
        const cityData = citiesData.find(
          item => item[0] === location.cities[i].name,
        );
        if (!cityData) {
          citiesData.push([
            location.cities[i].name,
            (location.cities[i].value * 100) / total,
          ]);
        }
      }

      return citiesData;
    };

    const dataLimit = (list: any) => {
      let len = 10;
      if (list.length < 10) {
        len = list.length;
      }
      return len;
    };

    const connectionCheck = (connectList: any, type: any) => {
      let isConnection = false;

      if (connectList && connectList.length > 0) {
        connectList.forEach((item: any) => {
          if (item.type === type) {
            isConnection = item.connect;
          }
        });
      }

      return isConnection;
    };

    const social = report && report?.data?.score && report?.data?.score?.social;
    const connectList = report && report?.data?.connectList;
    const isConnectionError = !connectionCheck(
      connectList,
      socialMediaType.toUpperCase(),
    );
    const socialMediaData =
      social && social.find((obj: any) => obj.type === socialMediaType);

    let dataCities: any[] = [];
    let dataCountries: any[] = [];
    let isError = false;
    let isNoDataError = false;
    let isNoCountryDataError = false;
    let isNoCityDataError = false;
    let errorMessageType;

    if (isConnectionError) {
      errorMessageType = `${socialMediaType.toLowerCase()}ErrorMessage`;
    } else if (!socialMediaData || socialMediaData.status != 'EXIST') {
      isError = true;
      errorMessageType = 'companySocialNotExist';
    }

    if (!isError && !isConnectionError) {
      const location = socialMediaData && socialMediaData.pageFansLocation;

      if (!location || location.length === 0) {
        isNoDataError = true;
        errorMessageType = 'noDataErrorMessage';
      } else {
        if (!location.countries || location.countries.length === 0) {
          isNoCountryDataError = true;
          errorMessageType = 'noDataErrorMessage';
        }
        if (!location.cities || location.cities.length === 0) {
          isNoCityDataError = true;
          errorMessageType = 'noDataErrorMessage';
        }
      }

      if (!isNoDataError) {
        let countriesData;
        let citiesData;
        if (!isNoCountryDataError) {
          countriesData = getCountriesData(location);
          dataCountries = countriesData;
        }

        if (!isNoCityDataError) {
          citiesData = getCitiesData(location);
          dataCities = citiesData;
        }
      }
    }
    const formattedCountryData = dataCountries.slice(1).map(item => ({
      x: item[0],
      y: item[1],
    }));
    const formattedCitiesData = dataCities.slice(1).map(item => ({
      x: item[0],
      y: item[1],
    }));

    return { dataCities, formattedCitiesData, formattedCountryData };
  }, [report]);

  const [data, setData] = useState(memoized?.formattedCitiesData);
  const [filter, setFilter] = useState('cities');
  const reversedData = [...data].reverse();
  return (
    <View flex-1>
      {memoized?.dataCities.length > 1 ? (
        <>
          <View row centerH>
            <View row center backgroundColor={colors.White} marginT-30>
              <TouchableOpacity
                style={{
                  borderWidth: 1,
                  borderColor:
                    filter === 'cities' ? Colors.orange40 : Colors.grey30,
                  borderRadius: 40,
                  width: 100,
                  padding: 10,
                  marginRight: 10,
                  backgroundColor:
                    filter === 'cities' ? Colors.orange40 : colors.White,
                }}
                onPress={() => {
                  setFilter('cities'), setData(memoized?.formattedCitiesData);
                }}>
                <View center spread>
                  <Text
                    style={{
                      color: filter === 'cities' ? Colors.white : Colors.grey30,
                      fontSize: 14,
                    }}>
                    Cities
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
            <View row center backgroundColor={Colors.white} marginT-30>
              <TouchableOpacity
                style={{
                  borderWidth: 1,
                  borderRadius: 40,
                  borderColor:
                    filter !== 'countries' ? Colors.grey30 : Colors.orange40,
                  width: 100,
                  padding: 10,
                  marginRight: 10,
                  backgroundColor:
                    filter === 'countries' ? Colors.orange40 : Colors.white,
                }}
                onPress={() => {
                  {
                    setFilter('countries'),
                      setData(memoized?.formattedCountryData);
                  }
                }}>
                <View center>
                  <Text
                    style={{
                      color:
                        filter !== 'countries' ? Colors.grey30 : Colors.white,
                      fontSize: 14,
                    }}>
                    Countries
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
          <View>
            <VictoryChart
              padding={70}
              theme={VictoryTheme.material}
              style={{
                background: { fill: Colors.white },
              }}
              horizontal>
              <VictoryAxis
                style={{ tickLabels: { fontSize: 10, fill: Colors.grey30, } }}
                tickFormat={(label) => {
                  if (label.length > 9) {
                    return label.substring(0, 8) + '...';
                  } else {
                    return label;
                  }
                }}
              />

              <VictoryBar
                barRatio={1.2}
                labels={({ datum }) => `${nFormatter(datum.y ?? 0, 2)}%`}
                labelComponent={<VictoryLabel dy={0} />}
                data={reversedData}
                style={{
                  data: {
                    fill: filter === 'cities' ? Colors.orange40 : Colors.orange40,
                    width: 15,
                  },
                }}
              />
            </VictoryChart>
          </View>
        </>
      ) : (
        <View margin-20>
          <Text>"You currently do not have a data..."</Text>
        </View>
      )}
    </View>
  );
};
export default Location;