Fakultas Ilmu Komputer UI

index.tsx 4.23 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);
Wulan Mantiri's avatar
Wulan Mantiri committed
42
    console.log(response);
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
50
51
52
      if (isAuthenticated) {
        navigation.navigate(ROUTES.checkout);
      } else {
        navigation.reset({
          index: 0,
          routes: [{ name: ROUTES.registration }],
        });
      }
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    } 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;
  };
73

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

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

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

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

export default ChoosePlan;