Fakultas Ilmu Komputer UI

index.tsx 3.84 KB
Newer Older
1
import React, { FC, useState, useCallback, useEffect } 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';
21
22
23
24

const ChoosePlan: FC = () => {
  const navigation = useNavigation();

25
26
27
  const [currentPage, setCurrentPage] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [values, setValues] = useState(initialValues);
28
  const [programs, setPrograms] = useState(defaultProgramRecommendations);
29

30
31
32
33
34
35
36
  const handleSubmit = async () => {
    setIsSubmitting(true);
    const response = await createCartApi(values);
    setIsSubmitting(false);

    if (response.success) {
      await setCache(CACHE_KEYS.cartId, response.data?.id);
37
      navigation.navigate(ROUTES.checkout, response.data);
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    } 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;
  };
58

59
60
61
62
63
64
65
66
67
68
69
70
71
  const getPrograms = useCallback(async () => {
    const cachedPrograms = await getCache(CACHE_KEYS.programRecommendations);
    setPrograms(
      cachedPrograms
        ? JSON.parse(cachedPrograms)
        : defaultProgramRecommendations,
    );
  }, []);

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

72
73
74
75
76
77
78
79
80
  const { isLoading, data: nutritionists = [] } = useApi(
    retrieveNutritionistsApi,
  );

  if (isLoading) {
    return <Loader />;
  }
  return (
    <WizardContainer
81
82
83
84
85
86
      currentStep={currentPage}
      setCurrentStep={setCurrentPage}
      onFinish={handleSubmit}
      finishButtonLabel="Bayar"
      isNextDisabled={isCurrentPageError()}
      isLoading={isSubmitting}
87
88
89
90
      components={[
        <ScrollView contentContainerStyle={layoutStyles}>
          <PricingList
            headerText="Pilih Rekomendasi Program Dietela"
91
            items={getRecommendedPrograms(programs).map((code) => ({
92
93
94
95
96
              ...dietPrograms[code],
              value: code,
              onReadMore: () =>
                navigation.navigate(ROUTES.programDetail, { id: code }),
            }))}
97
98
            value={values.program}
            onChange={(v) => handleChange('program', v)}
99
100
101
102
103
104
105
106
          />
        </ScrollView>,
        <ScrollView contentContainerStyle={layoutStyles}>
          <PricingList
            headerText="Pilih Nutrisionis Anda"
            items={nutritionists.map((nutritionist: Nutritionist) => ({
              title: nutritionist.full_name_and_degree,
              value: nutritionist.id,
107
108
109
              info: nutritionist.mastered_nutritional_problems
                .split(';')
                .slice(0, 3),
110
111
112
113
114
              onReadMore: () =>
                navigation.navigate(ROUTES.nutritionistDetail, {
                  id: nutritionist.id,
                }),
            }))}
115
116
            value={values.nutritionist}
            onChange={(v) => handleChange('nutritionist', v)}
117
118
119
120
121
122
123
124
          />
        </ScrollView>,
      ]}
    />
  );
};

export default ChoosePlan;