Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
11 kB
2
Indexable
Never
import React, { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, StyleSheet, useWindowDimensions } from 'react-native';
import { Text, TouchableOpacity, View } from 'react-native-ui-lib';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTranslation } from 'react-i18next';
import { useNavigation, useRoute } from '@react-navigation/native';

import { useColors } from '../../hooks';
import { GetAllCustodianAnalysis, GetCustomDatesCustodianAnalysis, GetSymbolAndSnapshot } from '../../api/matriks';
import { SymbolInfo } from '../../components/ui/Notification/SymbolInfo';

import {
  compareData,
  getAdjustedDates,
  sortByLandscape,
  sortStocksFunction,
} from './symbolDetailTabs/utils/custodian/CustodianFunctions';
import { BaseScreen, Icon, StockIcon } from '../../components/ui';
import { CustodianDetailCard } from '../../components/ui/Market/CustodianDetailCard';
import ModalController from '../../components/Modal/ModalController';
import { CustodianDetailCardLandscape } from '../../components/ui/Market/CustodianDetailCardLandscape';
import useOrientation from './hooks/useOrientation';

export function MarketCustodianDetail() {
  const {
    params: { symbolType, selectedTabIndex, headerLabel },
  }: any = useRoute();

  const { t, i18n } = useTranslation();
  const { colors }: any = useColors();
  const navigation = useNavigation();
  const { width, height } = useWindowDimensions();
  const orientation = useOrientation();

  const [isVisible, setIsVisible] = useState(false);
  const [allQueryDates, setAllQueryDates] = useState([]);
  const [comparisonResult, setComparisonResult] = useState([]);
  const [displayData, setDisplayData] = useState();

  //TODO imp. calender custom picker
  const [customDates, setCustomDates] = useState([]);
  const [selectedSort, setSelectedSort] = useState();
  const [isLandscape, setIsLandscape] = useState(false);
  const [sortLandscape, setSortLandspace] = useState({ field: '', order: '' });

  const isStockBased = selectedTabIndex === 0;
  const title = isStockBased ? t('stockBasedTitle') : t('companyBasedTitle');
  const detailTableLabel = isStockBased ? t('companyForTitle') : t('symbolForTitle');

  useEffect(() => {
    const generateQueryDates = async () => {
      try {
        const response = await getAdjustedDates();
        setAllQueryDates(response);
      } catch (error) {
        console.log('getAdjustedDates', error);
      }
    };
    generateQueryDates();
  }, []);

  const { data: symbolData, isLoading: symbolDataLoading } = GetSymbolAndSnapshot(symbolType, isStockBased);

  const { data: allDatesData, isLoading: allDatesDataLoading } = GetAllCustodianAnalysis(
    symbolType,
    allQueryDates,
    isStockBased,
  );
  const { data: customDatesData, isLoading: customDataLoading } = GetCustomDatesCustodianAnalysis(
    symbolType,
    customDates,
    isStockBased,
  );

  useEffect(() => {
    if (orientation === 'PORTRAIT') {
      setIsLandscape(false);
    } else {
      setIsLandscape(true);
    }
  }, [orientation]);

  useEffect(() => {
    if (allDatesData && allDatesData?.list?.length === 6) {
      const indicesToCompare = [0, 2, 3, 4, 5];
      const results: any = [];

      indicesToCompare.forEach(index => {
        const dataAtIndex = allDatesData.list[index];

        if (dataAtIndex && Array.isArray(dataAtIndex?.quantities) && dataAtIndex?.quantities?.length > 0) {
          const result = compareData(allDatesData, selectedTabIndex, i18n, index);
          results.push({
            calendarIndex: index,
            data: result,
          });
        }
      });
      setComparisonResult(results);
      setDisplayData(results[0]?.data);
    }
  }, [allDatesData]);

  //TEMP SOLUTIONS
  // useEffect(() => {
  //   const updateLayout = () => {
  //     const newWidth = Dimensions.get('window').width;
  //     const newHeight = Dimensions.get('window').height;
  //     setIsLandscape(newWidth > newHeight);
  //   };

  //   Dimensions.addEventListener('change', updateLayout);
  // }, [isLandscape]);
  //TEMP SOLUTIONS

  const externalChangeFilter = (index: number | undefined) => {
    if (comparisonResult[index]) {
      setDisplayData(comparisonResult[index - 1]?.data);
    }
  };

  const onChangeDate = (date: any) => {
    if (date[0] !== null && date[1] !== null) {
      setCustomDates(date);
    }
  };



  const sortStocks = (type: any) => {
    if (type === null) {
      setDisplayData(comparisonResult[0]?.data);
      setSelectedSort(null);
    } else {
      const sortedStocks = sortStocksFunction(displayData, type);
      setDisplayData(sortedStocks);
      setSelectedSort(type);
    }
  };

  const handleLandscapeSort = field => {
    const { sortedData, order } = sortByLandscape(displayData, sortLandscape, field);
    setSortLandspace({ field, order });
    setDisplayData(sortedData);
  };

  const portrait = useCallback(() => {
    return (
      <BaseScreen
        flex={1}
        header={{
          title,
          secondaryHeader: true,
        }}>
        <View>
          <View row marginH-24>
            {selectedTabIndex === 0 && symbolData ? (
              <SymbolInfo data={symbolData} />
            ) : (
              <CompanyBasedHeader data={headerLabel} />
            )}
            <TouchableOpacity
              onPress={() =>
                ModalController.showModal({
                  type: 'custodianSort',
                  fullScreenModal: true,
                  props: {
                    title: t('sortBy'),
                    selectedLabel: selectedSort,
                    sortStocks: sortStocks,
                  },
                })
              }>
              <Icon name="sort" width={32} height={32} fill={colors.secondaryText} />
            </TouchableOpacity>
          </View>
          <TouchableOpacity
            style={{ marginHorizontal: 24 }}
            onPress={() => {
              ModalController.showModal({
                type: 'dateRange',
                externalHeight: height / 1.4,
                props: {
                  initialDate: [allQueryDates[1], allQueryDates[1]],
                  showButton: true,
                  externalChangeFilter: externalChangeFilter,
                  onChange: onChangeDate,
                },
              });
            }}>
            <View row marginV-16>
              <Text primaryText marginR-4>
                {t('showPeriod')}
              </Text>
              <View center marginL-5>
                <Icon name="calendar" width={12} height={13} />
              </View>
            </View>
          </TouchableOpacity>
          {allDatesDataLoading ? (
            <View center>
              <ActivityIndicator style={styles.loadingIndicator} color={colors.action} animating size="large" />
            </View>
          ) : (
            <>
              <View row marginH-24 marginB-8>
                <View flex left>
                  <Text secondaryText body2>
                    {detailTableLabel}
                  </Text>
                </View>
                <View flex-3 right>
                  <Text secondaryText body2>
                    {t('quantity')}
                  </Text>
                </View>
                <View flex right>
                  <Text secondaryText body2>
                    {t('volume')}
                  </Text>
                </View>
              </View>

              <FlatList
                data={displayData}
                keyExtractor={(item, index) => `${index}+${item?.agent}`}
                renderItem={({ item, index }) => <CustodianDetailCard item={item} index={index} />}
                maxToRenderPerBatch={11}
                initialNumToRender={10}
                contentContainerStyle={{ paddingBottom: 392 }}
              />
            </>
          )}
        </View>
      </BaseScreen>
    );
  }, [isLandscape, displayData]);

  const landscape = useCallback(() => {
    return (
      <SafeAreaView>
        <View marginT-20>
          <View row centerV>
            <TouchableOpacity centerV marginR-14 marginB-6 onPress={() => navigation.goBack()}>
              <Icon name={'back'} height={18} width={18} fill={colors.primaryText} />
            </TouchableOpacity>
            {selectedTabIndex === 0 && symbolData ? (
              <SymbolInfo data={symbolData} />
            ) : (
              <CompanyBasedHeader data={headerLabel} />
            )}
            <Text primaryText heading3 marginH-42>
              {title}
            </Text>

            <TouchableOpacity
              flex
              right
              onPress={() => {
                ModalController.showModal({
                  type: 'dateRange',
                  externalHeight: height / 1.4,
                  props: {
                    initialDate: [allQueryDates[1], allQueryDates[1]],
                    showButton: true,
                    externalChangeFilter: externalChangeFilter,
                  },
                });
              }}>
              <View row>
                <Text primaryText body2 marginR-4>
                  {t('showPeriod')}
                </Text>
                <View center marginL-5>
                  <Icon name="calendar" width={12} height={13} />
                </View>
              </View>
            </TouchableOpacity>
          </View>
          {allDatesDataLoading ? (
            <View center>
              <ActivityIndicator style={styles.loadingIndicator} color={colors.action} animating size="large" />
            </View>
          ) : (
            <CustodianDetailCardLandscape
              data={displayData}
              title={title}
              handleLandscapeSort={handleLandscapeSort}
              sortLandscape={sortLandscape}
            />
          )}
        </View>
      </SafeAreaView>
    );
  }, [isLandscape, displayData]);

  const renderPortraitMode = () => (isLandscape ? landscape() : portrait());

  return <>{renderPortraitMode()}</>;
}

const CompanyBasedHeader = ({ data }) => (
  <View row centerV flex>
    <StockIcon name={data} size={32} />
    <Text primaryText marginL-10>
      {data}
    </Text>
  </View>
);

const styles = StyleSheet.create({
  titleStyle: {
    fontSize: 18,
    fontWeight: '500',
  },
  calendarStyle: {
    fontWeight: '500',
    fontSize: 12,
  },
  loadingIndicator: {
    marginVertical: 100,
  },
  container: {
    flexDirection: 'row',
    marginTop: 20,
    marginHorizontal: 24,
  },
  companyText: {
    flex: 2,
    textAlign: 'left',
    marginLeft: 16,
  },
  quantityText: {
    flex: 1,
    textAlign: 'center',
  },
  volumeText: {
    flex: 1,
    textAlign: 'right',
    marginRight: 16,
  },
});
Leave a Comment