Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
9.0 kB
2
Indexable
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react-native/no-inline-styles */
import React, { useState } from 'react';
import { View, Text } from 'react-native-ui-lib';
import { TouchableOpacity } from 'react-native-gesture-handler';
import colors from '../../rb-constants/colors';
import { GridView } from '../../rb-components/Grid';
import DateFormat from '../../rb-components/DateFormat';
import {
  VictoryAxis,
  VictoryBar,
  VictoryChart,
  VictoryLabel,
  VictoryTheme,
} from 'victory-native';
import { nFormatter } from '../../../utils/number_formatter';

type Props = {
  report: any;
  company?: any;
};

const Demographics = ({ report, company }: Props) => {
  const [filter, setFilter] = useState('');

  const dataOperation = (list: string | any[]) => {
    const result = [['', '']];
    let total = 0;
    for (let i = 0; i < list.length; i++) {
      if (list[i].name.search('Change') === -1) {
        total += list[i].sessions;
      }
    }
    if (total === 0) {
      return null;
    }
    for (let i = 0; i < list.length; i++) {
      if (list[i].name.search('Change') === -1) {
        const temp = [];
        temp.push(list[i].name);
        temp.push((list[i].sessions * 100) / total);
        result.push(temp);
      }
    }
    return result;
  };

  const splitData = (list: string | any[], keyword: string) => {
    const result = [['', '']];
    let total = 0;
    for (let i = 0; i < list.length; i++) {
      if (list[i].name.search('Change') === -1) {
        const splitData = list[i].name.split('|');
        if (splitData[0] === keyword) {
          total += list[i].sessions;
        }
      }
    }
    if (total === 0) {
      return null;
    }
    for (let i = 0; i < list.length; i++) {
      if (list[i].name.search('Change') === -1) {
        const splitData = list[i].name.split('|');
        if (splitData[0] === keyword) {
          const temp = [];
          temp.push(splitData[1]);
          temp.push((list[i].sessions * 100) / total);
          result.push(temp);
        }
      }
    }
    return result;
  };

  const renderChart = () => {
    const data = report?.data;

    const genderData = [['', '']];
    let ageData: string[][] | null = [];
    const ageErrorData = [
      ['', ''],
      ['25-34', 47.3882945248584],
      ['35-44', 29.72519404237466],
      ['45-54', 6.083490664988462],
    ];
    const genderErrorData = [
      ['', ''],
      ['male', 45],
      ['female', 65],
    ];
    let male;
    let female;
    let isErrorGender = false;
    let isErrorAge = false;
    const gender = data?.analytics && data?.analytics.gender;
    const age = data?.analytics && data?.analytics.age;
    const genderAndAge = data?.analytics && data?.analytics.genderAndAge;
    if (!gender || gender.length === 0) {
      isErrorGender = true;
    }
    if (!isErrorGender) {
      male = gender.find((item: { name: string }) => item.name === 'male');
      female = gender.find((item: { name: string }) => item.name === 'female');
      if (male) {
        genderData?.push([male.name, male.sessions]);
      }
      if (female) {
        genderData?.push([female.name, female.sessions]);
      }
    }

    if (
      !age ||
      age.length === 0 ||
      !genderAndAge ||
      genderAndAge.length === 0
    ) {
      isErrorAge = true;
    }
    if (!isErrorAge) {
      if (filter === 'male') {
        ageData = splitData(genderAndAge, 'male');
      } else if (filter === 'female') {
        ageData = splitData(genderAndAge, 'female');
      } else {
        ageData = dataOperation(age);
      }
      ageData?.sort();
    }

    const chartData = ageData?.map(item => ({ x: item[0], y: item[1] })) || [];

    return chartData;
  };

  return (
    <>
      <View flex spread marginV-5 paddingB-0>
        <View row centerH>
          <View row center backgroundColor={colors.White} marginT-30>
            <TouchableOpacity
              style={{
                borderWidth: 1,
                borderColor:
                  filter === 'all' || filter === ''
                    ? colors.Orange
                    : colors.grey,
                borderRadius: 40,
                width: 100,
                padding: 10,
                marginRight: 10,
                backgroundColor: filter === '' ? colors.Orange : colors.White,
              }}
              onPress={() => setFilter('')}>
              <View center spread>
                <Text
                  style={{
                    color: filter === '' ? colors.white : colors.gray,
                  }}>
                  ALL
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          <View row center backgroundColor={colors.White} marginT-30>
            <TouchableOpacity
              style={{
                borderWidth: 1,
                borderRadius: 40,
                borderColor: filter !== 'male' ? colors.grey : colors.Orange,
                width: 100,
                padding: 10,
                marginRight: 10,
                backgroundColor:
                  filter === 'male' ? colors.Orange : colors.White,
              }}
              onPress={() => setFilter('male')}>
              <View center>
                <Text
                  style={{
                    color: filter !== 'male' ? colors.gray : colors.White,
                  }}>
                  MALE
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          <View row center backgroundColor={colors.White} marginT-30>
            <TouchableOpacity
              style={{
                borderWidth: 1,
                borderColor: filter !== 'female' ? colors.grey : colors.Orange,
                borderRadius: 40,
                width: 100,
                padding: 10,
                marginRight: 10,
                backgroundColor:
                  filter === 'female' ? colors.Orange : colors.White,
              }}
              onPress={() => setFilter('female')}>
              <View center>
                <Text
                  style={{
                    color: filter !== 'female' ? colors.gray : colors.White,
                  }}>
                  FEMALE
                </Text>
              </View>
            </TouchableOpacity>
          </View>
        </View>
        <View center>
          <VictoryChart
            theme={VictoryTheme.material}
            style={{
              background: { fill: colors.white },
            }}
            domainPadding={{ x: 25 }}
          >
            <VictoryLabel
              x={40}
              y={10}
              style={{ fontSize: 20, fill: colors.grey }}
            />

            <VictoryAxis
              dependentAxis
              tickFormat={tick => `${tick}%`}
              style={{
                tickLabels: {
                  fill: colors.grey,
                  fontSize: 12,
                  padding: 5,
                  verticalAnchor: 'middle', // Align the rotated labels in the middle
                  textAnchor: 'end', // Align the rotated labels to the end of the tick
                },
                axis: { stroke: colors.grey },
                grid: { stroke: colors.grey, strokeDasharray: "none" }
              }}
            />
         
            <VictoryAxis
              style={{
                grid: { stroke: 'none' },
                tickLabels: {
                  fontSize: 14,
                  fill: colors.grey,
                  angle: 30,
                },
              }}
            />
            <VictoryBar
              barRatio={1.2}
              labels={({ datum }) => `${nFormatter(datum.y ?? 0, 2)}`}
              data={renderChart()}
              style={{
                data: {
                  fill:
                    filter === 'male'
                      ? colors.Orange
                      : filter === ''
                        ? colors.Orange
                        : colors.OrangeLightest,
                  width: 25,
                },
              }}
            />
          </VictoryChart>

        </View>
        {filter === 'all' ? null : (
          <View row center marginB-15>
            {filter === 'male' && (
              <View row center>
                <View
                  width={20}
                  height={20}
                  backgroundColor={colors.Orange}
                />
                <Text marginL-10>Male</Text>
              </View>
            )}
            {filter === 'female' && (
              <View center row>
                <View
                  width={20}
                  height={20}
                  backgroundColor={colors.OrangeLighter}
                />
                <Text marginL-5>Female</Text>
              </View>
            )}
          </View>
        )}
      </View>
    </>
  );
};

export default Demographics;