Untitled

 avatar
user_2022652731
plain_text
3 years ago
18 kB
3
Indexable
import React, { FunctionComponent, useRef, useState } from 'react';
import { FlatList, Pressable, View } from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { Modalize } from 'react-native-modalize';
import { Host } from 'react-native-portalize';
import { useSelector } from 'react-redux';
import AppCalender from '../../../../../../components/app-calender';
import AppInput from '../../../../../../components/app-input';
import AppModal from '../../../../../../components/app-modal';
import AppText from '../../../../../../components/app-text';
import AppTextAreaInput from '../../../../../../components/app-text-area';
import ArtisanPane from '../../../../../../components/artisan-pane';
import AppButton from '../../../../../../components/button';
import Chip from '../../../../../../components/chip';
import Header from '../../../../../../components/header';
import InfoInput from '../../../../../../components/info-input';
import AppScreen from '../../../../../../components/screen';
import Select from '../../../../../../components/select';
import SelectOption from '../../../../../../components/select-option';
import Separator from '../../../../../../components/separator';
import Sheet from '../../../../../../components/sheet';
import { colors, headerHeight, height } from '../../../../../../config/config';
import { fontsizes, wp } from '../../../../../../config/fonts';
import { Map } from '../../../../../../constants/images';
import { routeNames } from '../../../../../../constants/routeNames';
import { formatData } from '../../../../../../helpers/formatList';
import orderService from '../../../../../../redux/orders/orderServices';
import { RootState } from '../../../../../../redux/store';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import HUMaps from '../../../../../../components/HUMaps';
import HUGooglePlacesAutoComplete from '../../../../../../components/HUGooglePlacesAutoComplete';
import { HIRE_US_API_KEY } from '../../../../../../HUvariables';


const OrderDetails: FunctionComponent = (_props: any) => {
  const { navigation, route } = _props;
  const [showTimeModal, setShowTimeModal] = useState(false);
  const [showDateModal, setShowDateModal] = useState(false);
  const [isCalenderVisible, setIsCalenderVisible] = useState(false);
  const [selectedDate, setSelectedDate] = useState('00/00/00');
  const [selectedTime, setSelectedTime] = useState<string>('00:00am');

  const [selectedServices, setSelectedServices] = useState<string[]>([]);
  const [highlightedServices, setHighlightedServices] = useState<string[]>([]);
  const [error, setError] = useState<any>({});

  const sheetRef = useRef<Modalize>(null);

  const { allWorkingArtisans } = useSelector(
    (state: RootState) => state.profileState,
  );
  const { isClient, user } = useSelector((state: RootState) => state.authState);
  const artisan: any = allWorkingArtisans.find(
    (el: any) => el._id === route.params,
  );

  const openSheet = () => {
    setHighlightedServices(selectedServices);
    sheetRef?.current?.open();
  };
  const closeSheet = () => {
    sheetRef?.current?.close();
    setSelectedServices(highlightedServices);
  };

  const time = [
    { time: '07:00am' },
    { time: '08:00am' },
    { time: '09:00am' },
    { time: '10:00am' },
    { time: '11:00am' },
    { time: '12:00pm' },
    { time: '01:00pm' },
    { time: '02:00pm' },
    { time: '03:00pm' },
    { time: '04:00pm' },
    { time: '05:00pm' },
    { time: '06:00pm' },
  ];

  const handleShowCalender = () => {
    setShowTimeModal(true);
    setIsCalenderVisible(true);
  };

  const handleSelectedDate = (date: any) => {
    setSelectedDate(date);
    setIsCalenderVisible(false);
    setShowDateModal(false);
  };

  const handleCloseDate = () => {
    setIsCalenderVisible(false);
    setShowDateModal(false);
  };

  const handleServiceSelected = () => {
    // setSelectedServices(highlightedServices)
    closeSheet();
  };

  const handleOnSelectTime = (time: string) => {
    setSelectedTime(time);
    setShowTimeModal(false);
  };

  const _renderWorks = (time: any, index: number) => {
    const selected = time === selectedTime;
    return (
      <Chip
        extraStyles={{
          flex: 1,
          margin: 10,
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: selected ? colors.purple_light : colors.white,
          borderWidth: 1,
          borderColor: colors.grey_dark_1,

          // marginBottom: 0,
          paddingVertical: 20,
          paddingHorizontal: 10,
        }}
        labelStyle={{
          padding: 5,
          color: selected ? colors.white : colors.black,
        }}
        text={time}
        key={index}
        selected={time === selectedTime}
        onPress={() => handleOnSelectTime(time)}
      />
    );
  };

  const [userInfo, setUserInfo] = useState({
    address: '',
    description: '',
  });

  const handleSubmit = () => {
    // const error = [
    //   highlightedServices.length,
    //   selectedDate.trim() === '00/00/00' ? 0 : null,
    //   selectedTime.trim() === '00:00am' ? 0 : null,
    //   userInfo?.address.trim().length,
    // ].includes(0);

    // [
    //   {servies: highlightedServices.length},
    //   {time: selectedTime},
    //   {date: selectedDate},
    //   {address: userInfo?.address.trim().length},
    // ].forEach((_: any) => {
    //   ['00/00/00', '00:00am', 0, ''].includes(_)
    // })
    const allErrors = {};
    const fields = ['services', 'time', 'date', 'address'];
    const fieldsErrorMessage = [
      'Select at least one services',
      'Time is Required',
      'Date is Required',
      'Address is Required',
    ];
    const fieldsValue = [
      highlightedServices.length,
      selectedTime,
      selectedDate,
      userInfo?.address.trim().length,
    ];
    fieldsValue.forEach((_: any, i: number) => {
      ['00/00/00', '00:00am', 0, ''].includes(_)
        ? (allErrors[fields[i]] = fieldsErrorMessage[i])
        : null;
    });

    // setError()
    if (Object.entries(allErrors).length) {
      setError(allErrors);
    } else {
      setError({});
      navigation.navigate(routeNames.CONFIRM_ORDER, {
        // services: artisan.services.filter(el => highlightedServices.includes(el.title)),
        orderedServices: highlightedServices,
        selectedDate,
        selectedTime,
        artisanId: artisan._id,
        userInfo,
      });
    }
  };

  //Zucci: get back to this later.
  // const handleSelected = (item: string) => {
  //     if (selectedServices.includes(item) || highlightedServices.includes(item)) {
  //         const copiedSelectedServices = [...selectedServices];
  //         const copiedHighlightedServices = [...highlightedServices];
  //         const newServices = copiedSelectedServices.filter((service, index) => service !== item)
  //         const newHighlightedServices = copiedHighlightedServices.filter((service, index) => service !== item)
  //         setSelectedServices(newServices);
  //         setHighlightedServices(newHighlightedServices)

  //     } else {
  //         setHighlightedServices((services) => [...services, item])
  //     }
  // }
  const handleSelected = (item: string) => {
    if (highlightedServices.includes(item)) {
      const newSelected = highlightedServices.filter(elitem => elitem !== item);
      setHighlightedServices(newSelected);
    } else {
      setHighlightedServices([item, ...highlightedServices]);
    }
  };

  const shouldDisableButton = () => {
    // disable the button if some important fields are empty
    return false; //dummy
  };

  console.log(artisan)



  return (
    <>
      {/* <Header routeName="Order Detail" leftAreaDefault={false} /> */}
      <KeyboardAwareScrollView>
        {/* <AppScreen extraStyles={{ paddingHorizontal: 0, paddingVertical: 0, }}> */}
        <View
          style={{
            flex: 1,
            backgroundColor: colors.background,
            padding: 20,
            paddingBottom: 20,
          }}>
          <ArtisanPane
            readonly
            showLocation={true}
            showOnline={true}
            username={`${artisan.user.firstName} ${artisan.user.lastName}`}
            showStatus={false}
            service={artisan.title}
            avatarUri={artisan.user.image}
          />
          <View style={{ flex: 1, marginVertical: 10 }}>
            <View
              style={{
                height: undefined,
                width: undefined,
                flexDirection: 'row',
                flexWrap: 'wrap',
              }}>
              {selectedServices.map((item: any, index: number) => (
                <Chip key={index} text={item} extraStyles={{ marginRight: 5 }} />
              ))}
            </View>
            <Select
              placeholder="Select services"
              customHandling
              onPress={openSheet}
            />
            {error['services'] && (
              <AppText
                text={error['services']}
                extraStyles={{
                  marginTop: -10,
                  color: '#dc3545',
                  paddingHorizontal: 10,
                }}
              />
            )}
            <Separator>
              <>
                <View style={{ flex: 1, marginRight: 10 }}>
                  <InfoInput
                    label="Time"
                    value={selectedTime}
                    // extraStyles={{marginRight: 10}}
                    onPress={() => setShowTimeModal(true)}
                  />
                  {error['time'] && (
                    <AppText
                      text={error['time']}
                      extraStyles={{
                        marginTop: -10,
                        color: '#dc3545',
                        paddingHorizontal: 10,
                      }}
                    />
                  )}
                </View>
                <View style={{ flex: 1 }}>
                  <InfoInput
                    label="Date"
                    value={selectedDate}
                    onPress={() => {
                      setIsCalenderVisible(true);
                      setShowDateModal(true);
                    }}
                  />
                  {error['date'] && (
                    <AppText
                      text={error['date']}
                      extraStyles={{
                        marginTop: -10,
                        color: '#dc3545',
                        paddingHorizontal: 10,
                      }}
                    />
                  )}
                </View>
              </>
            </Separator>
            <View
              style={{
                height: 200,
                borderRadius: 10,
                justifyContent: 'center',
                alignItems: 'center',
              }}>
              <HUMaps
                longitude={7.059688216014393}
                latitude={5.513513513513513}
                latitudeDelta={0.015}
                longitudeDelta={0.0121}
              />
            </View>
            {/* onChangeText={text => setUserInfo({ ...userInfo, address: text })} */}
            <View style={{ flex: 1, zIndex: 500000, backgroundColor: 'red', }}>
              <GooglePlacesAutocomplete
                placeholder="Search"
                enablePoweredByContainer={false}
                minLength={2} // minimum length of text to search
                listViewDisplayed="auto" // true/false/undefined
                fetchDetails={true}
                keyboardShouldPersistTaps='always'
                renderDescription={row => row.description} // custom description render
                onPress={(data, details = null) => {
                  console.log('worrrrr', data)
                }}
                query={{
                  // available options: https://developers.google.com/places/web-service/autocomplete
                  key: HIRE_US_API_KEY,
                  location: 'nigeria',
                  language: 'en', // language of the results
                }}
                styles={{
                  description: {
                    fontWeight: 'bold',
                    color: colors.labelColor,
                    zIndex: 500000
                  },
                  predefinedPlacesDescription: {
                    color: colors.labelColor,
                    zIndex: 500000
                  },
                  textInput: {
                    color: colors.labelColor,
                    zIndex: 500000
                  },
                  listView: {
                    elevation: 1,
                    backgroundColor: 'white',
                    position: 'absolute', // and the absolute position.
                    zIndex: 500000
                  },
                  container: { zIndex: 500000, flex: 0 },
                  row: { zIndex: 500000 },
                  poweredContainer: { zIndex: 500000 },
                  textInputContainer: { zIndex: 500000 }
                }}
                //currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
                currentLocationLabel="Current location"
                nearbyPlacesAPI="GooglePlacesSearch" // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
                GoogleReverseGeocodingQuery={{
                  // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
                }}
                GooglePlacesSearchQuery={{
                  // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                  rankby: 'distance',
                }}
                filterReverseGeocodingByTypes={[
                  'street_address',

                ]} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities

                debounce={200}
              />
            </View>
            <AppTextAreaInput
              label="Description (optional)"
              multiline
              numberOfLines={5}
              onChangeText={text =>
                setUserInfo({ ...userInfo, description: text })
              }
            />
          </View>

          <AppButton
            title="continue"
            isDisabled={shouldDisableButton()}
            onPress={handleSubmit}
            extraButtonStyles={{ marginVertical: 20 }}
          />
        </View>

        {/* </AppScreen> */}
        <AppModal
          isVisible={showTimeModal}
          onBackDrop={() => setShowTimeModal(false)}>
          <View
            style={{
              height: undefined,
              padding: 15,
              borderRadius: 10,
              width: '100%',
              backgroundColor: colors.white,
            }}>
            <FlatList
              numColumns={3}
              showsVerticalScrollIndicator={false}
              // contentContainerStyle={{backgroundColor: 'red', padding: 20}}
              keyExtractor={item => Math.floor(Math.random() * 100) + item}
              data={formatData(time, 3)}
              renderItem={({ item, index }) =>
                item.empty ? (
                  <View
                    style={{
                      flex: 1,
                      backgroundColor: 'transparent',
                      margin: 15,
                    }}
                  />
                ) : (
                  _renderWorks(item.time, index)
                )
              }
            />
            {/* <AppButton
              title="cancel"
              mode="small"
              extraButtonStyles={{marginTop: wp(20), margin: 10}}
              onPress={() => setShowTimeModal(false)}
            /> */}
          </View>
        </AppModal>
        <AppModal
          isVisible={showDateModal}
          onBackDrop={() => setShowDateModal(false)}>
          <View
            style={{
              height: undefined,
              width: '100%',
              backgroundColor: colors.white,
              borderRadius: 10,
            }}>
            <AppCalender
              isVisible={isCalenderVisible}
              handleClose={handleCloseDate}
              handleConfirm={(date: any) => handleSelectedDate(date)}
            />
          </View>
        </AppModal>
        <Sheet
          sheetRef={sheetRef}
          onPressButton={closeSheet}
          enableSlideToClose={true}
          disableBackDrop={false}
          onBackPress={closeSheet}>
          <View
            style={{
              height: undefined,
              width: '100%',
              paddingHorizontal: 15,
              justifyContent: 'space-between',
            }}>
            <AppScreen extraStyles={{ paddingHorizontal: 0 }}>
              <>
                {artisan.services.map((item: any, index: number) => (
                  // <SelectOption
                  //     isSelected={selectedServices.includes(item.title) || highlightedServices.includes(item) ? true : false}
                  //     onPress={() => handleSelected(item)}

                  //     title={item.title} key={index} />
                  <SelectOption
                    isSelected={highlightedServices.includes(item.title)}
                    onPress={() => handleSelected(item.title)}
                    title={item.title}
                    key={index}
                  />
                ))}
              </>
            </AppScreen>
            <AppButton
              title="continue"
              extraButtonStyles={{ marginVertical: wp(40) }}
              onPress={() => handleServiceSelected()}
            />
          </View>
        </Sheet>
      </KeyboardAwareScrollView>
    </>
  );
};

export default OrderDetails;
Editor is loading...