Fakultas Ilmu Komputer UI

index.tsx 4.26 KB
Newer Older
Wulan Mantiri's avatar
Wulan Mantiri committed
1
import React, { FC, useState, useCallback, useEffect, useContext } from 'react';
2
import { ScrollView } from 'react-native';
3
import { useNavigation } from '@react-navigation/native';
4

5
import { WizardContainer, Loader, Toast } from 'components/core';
6
7
import CACHE_KEYS from 'constants/cacheKeys';
import * as ROUTES from 'constants/routes';
8
9
10
11
12
import { useApi } from 'hooks';
import {
  dietPrograms,
  defaultProgramRecommendations,
} from 'constants/dietelaProgram';
13
14
import { retrieveNutritionistsApi } from 'services/nutritionists';
import { Nutritionist } from 'services/nutritionists/models';
15
import { createCartApi } from 'services/payment';
16
import { layoutStyles } from 'styles';
17
import { setCache, getCache } from 'utils/cache';
18
19

import { PricingList } from './components';
20
import { initialValues, getRecommendedPrograms } from './schema';
Wulan Mantiri's avatar
Wulan Mantiri committed
21
import { UserContext } from 'provider';
22
23
24

const ChoosePlan: FC = () => {
  const navigation = useNavigation();
Wulan Mantiri's avatar
Wulan Mantiri committed
25
  const { user, isAuthenticated } = useContext(UserContext);
26

27
28
29
  const [currentPage, setCurrentPage] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [values, setValues] = useState(initialValues);
30
  const [programs, setPrograms] = useState(undefined);
31

32
33
  const handleSubmit = async () => {
    setIsSubmitting(true);
Wulan Mantiri's avatar
Wulan Mantiri committed
34
35
36
37
38
39
40
    const payload = user.id
      ? {
          ...values,
          user: user.id,
        }
      : values;
    const response = await createCartApi(payload);
41
    setIsSubmitting(false);
42

43
44
    if (response.success) {
      await setCache(CACHE_KEYS.cartId, response.data?.id);
Wulan Mantiri's avatar
Wulan Mantiri committed
45
46
47
48
49
      if (isAuthenticated) {
        navigation.navigate(ROUTES.checkout);
      } else {
        navigation.reset({
          index: 0,
50
51
52
          routes: [
            { name: ROUTES.registration, params: { fromChoosePlan: true } },
          ],
Wulan Mantiri's avatar
Wulan Mantiri committed
53
54
        });
      }
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    } else {
      Toast.show({
        type: 'error',
        text1: 'Gagal menyimpan data',
        text2: 'Terjadi kesalahan pada sisi kami. Silakan coba lagi',
      });
    }
  };

  const handleChange = (name: string, value: string) => {
    setValues({
      ...values,
      [name]: value,
    });
  };

  const isCurrentPageError = (): boolean => {
    const fieldName = currentPage === 1 ? 'program' : 'nutritionist';
    return values[fieldName] === null;
  };
75

76
77
78
79
80
81
82
83
84
85
86
87
88
  const getPrograms = useCallback(async () => {
    const cachedPrograms = await getCache(CACHE_KEYS.programRecommendations);
    setPrograms(
      cachedPrograms
        ? JSON.parse(cachedPrograms)
        : defaultProgramRecommendations,
    );
  }, []);

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

89
90
91
92
  const { isLoading, data: nutritionists = [] } = useApi(
    retrieveNutritionistsApi,
  );

93
  if (isLoading || programs === undefined) {
94
95
96
97
    return <Loader />;
  }
  return (
    <WizardContainer
98
99
100
101
102
103
      currentStep={currentPage}
      setCurrentStep={setCurrentPage}
      onFinish={handleSubmit}
      finishButtonLabel="Bayar"
      isNextDisabled={isCurrentPageError()}
      isLoading={isSubmitting}
104
105
106
107
      components={[
        <ScrollView contentContainerStyle={layoutStyles}>
          <PricingList
            headerText="Pilih Rekomendasi Program Dietela"
108
            items={getRecommendedPrograms(programs).map((code) => ({
109
110
111
112
113
              ...dietPrograms[code],
              value: code,
              onReadMore: () =>
                navigation.navigate(ROUTES.programDetail, { id: code }),
            }))}
114
115
            value={values.program}
            onChange={(v) => handleChange('program', v)}
116
117
118
119
120
121
122
123
          />
        </ScrollView>,
        <ScrollView contentContainerStyle={layoutStyles}>
          <PricingList
            headerText="Pilih Nutrisionis Anda"
            items={nutritionists.map((nutritionist: Nutritionist) => ({
              title: nutritionist.full_name_and_degree,
              value: nutritionist.id,
124
125
126
              info: nutritionist.mastered_nutritional_problems
                .split(';')
                .slice(0, 3),
127
128
              onReadMore: () =>
                navigation.navigate(ROUTES.nutritionistDetail, {
129
                  ntr: nutritionist,
130
131
                }),
            }))}
132
133
            value={values.nutritionist}
            onChange={(v) => handleChange('nutritionist', v)}
134
135
136
137
138
139
140
141
          />
        </ScrollView>,
      ]}
    />
  );
};

export default ChoosePlan;