Untitled

 avatar
unknown
plain_text
6 months ago
14 kB
4
Indexable
import React, { useEffect, useCallback, useState, useRef } from "react";
import {
  Alert,
  FlatList,
  SafeAreaView,
  StyleSheet,
  TouchableOpacity,
  View,
  Image,
  InteractionManager,
  ActivityIndicator
} from "react-native";
import FastImage from "react-native-fast-image";
import { ms, mvs } from "react-native-size-matters";
import { useFocusEffect } from "@react-navigation/native";
import images from "../../../../assets/images/images";
import CompanyTabSection from "../../../../components/CompanyTabSection";
import CustomButton from "../../../../components/CustomButton";
import Loader from "../../../../components/Loader";
import ServiceCard from "../../../../components/Servicecard";
import EText from "../../../../components/Text";
import { colors } from "../../../../constants/colors";
import { FontType } from "../../../../constants/fonts";
import { TAB_PACKAGES, TAB_SERVICES } from "../../../../utils/appConstants";
import { storageRead } from "../../../../utils/storageUtils";
import { useBusinessHome } from "./BusinessHomeContext";
import ImagePicker from "react-native-image-crop-picker";
import ProgressiveImage from "../../../../components/ProgressiveImage";
import { AirbnbRating } from "react-native-ratings";
import CustomAlertComponent from "../../../../components/CustomAlertBox";
import { t } from "i18next";

const BusinessHomeScreen = ({ navigation}) => {
  const {
    isLoading,
    businessHomeServiceArray,
    createServiceData,
    getBusinessHomeServices,
    createService,
    cloudinaryImageUpload,
    updateBusinessLogo,
    getBusinessProfiles,
    cloneBusinessService,
    publishBusinessService,
    unpublishBusinessService,
    deleteBusinessService,
    cloudinaryResponse,
    updateBusinessLogoResponse,
    getBusinessProfileResponse,
    resetServiceDetails,
    isUpdated, setIsUpdated, totalServices,
    isFetchingMore,setIsFetchingMore,
    totalPages,
    currentPage,
  } = useBusinessHome();
  const flatListRef = useRef(null);

  const [businessAccountDetail, setBusinessAccountDetail] = useState();
  const [isNewServiceCreated, setIsNewServiceCreated] = useState(false);
  const [currentTab, setCurrentTab] = useState(TAB_SERVICES);
  const [alertOpen, setAlertOpen] = useState(false);

  const [isCamera, setIsCamera] = useState(false);
  const [image, setImage] = useState();
  const [businessLogo, setBusinessLogo] = useState(null);
  const [businessProfile, setBusinessProfile] = useState(null);
  const [reloadFlag, setReloadFlag] = useState(false);
  const [shouldScrollToTop, setShouldScrollToTop] = useState(false);
  const checkForUserLogin = async () => {
    const accountDetail = await storageRead("user_details");
    setBusinessAccountDetail(accountDetail);
  };
  const scrollToTop = () => {
    if (flatListRef.current) {
      flatListRef.current.scrollToOffset({ offset: 0, animated: true });
    }
  };
  useFocusEffect(
    useCallback(() => {
      checkForUserLogin();
    }, [])
  );
  useEffect(() => {
    if (isUpdated) {
      setShouldScrollToTop(true);
    }
  }, [isUpdated]);


  const loadMoreServices = () => {
    if (currentPage < totalPages && !isFetchingMore) {
      getBusinessHomeServices(businessAccountDetail?.accountId, currentPage + 1);
    }
  };
  useEffect(() => {
    if (businessAccountDetail) {
      getBusinessHomeServices(businessAccountDetail?.accountId ,1);
      getBusinessProfiles(businessAccountDetail?.accountId);
      resetServiceDetails();
      console.log("check1 Data",shouldScrollToTop)
      if (shouldScrollToTop) {
        console.log("check2",shouldScrollToTop)
        scrollToTop();
        setShouldScrollToTop(false); // Reset scroll state after scrolling
        setIsUpdated(false); // Reset isUpdated state after scrolling
      }
    }
  }, [businessAccountDetail, isNewServiceCreated, reloadFlag],scrollToTop);

  useEffect(() => {
    if (createServiceData?.serviceId) {
      navigation.navigate("SelectService", {
        serviceId: createServiceData?.serviceId,
        isEdit: false,
        newCreation: true,
      });
      setShouldScrollToTop(true); // Set scroll state after new service creation
    }
  }, [createServiceData, navigation]);

  useEffect(() => {
    if (getBusinessProfileResponse) {
      const profile = getBusinessProfileResponse.body?.[0];
      setBusinessProfile(profile);
    }
  }, [getBusinessProfileResponse]);

  useEffect(() => {
    if (cloudinaryResponse?.secure_url) {
      updateBusinessLogo(businessAccountDetail?.accountId, {
        logoUrl: cloudinaryResponse?.secure_url,
        logoObj: {
          assetId: cloudinaryResponse?.asset_id,
          deleteToken: cloudinaryResponse?.delete_token,
          mediaUrl: cloudinaryResponse?.secure_url,
          bytes: cloudinaryResponse?.bytes,
          createdAt: cloudinaryResponse?.created_at,
          mediaType: cloudinaryResponse?.type,
          mediaFormat: cloudinaryResponse?.format,
        },
      });
    }
  }, [cloudinaryResponse, businessAccountDetail]);

  useEffect(() => {
    if (updateBusinessLogoResponse?.head?.success) {
      setBusinessLogo(image?.path);
      setReloadFlag(!reloadFlag);
      setShouldScrollToTop(isUpdated); // Set scroll state after logo update
    }
  }, [updateBusinessLogoResponse, image]);

  const onPressAddNewService = () =>
    createService(businessAccountDetail?.accountId);

  const showServiceActionPopup = (type, item) => {
    const actions = {
      1: { keyword: item?.isPublic ? "Unpublish" : "Publish", action: publishUnpublishService },
      2: { keyword: "Clone", action: cloneService },
      3: { keyword: "Delete", action: deleteService },
    };

    const { keyword, action } = actions[type];

    Alert.alert(
      "Are you sure?",
      `Are you sure you want to ${keyword}?`,
      [
        { text: "Yes", onPress: () => {action(item)
         }},
        { text: "No" },
      ]
    );
  };

  const publishUnpublishService = async (item) => {
    const action = item?.isPublic
      ? unpublishBusinessService
      : publishBusinessService;
    await action(item?.serviceId);
    setReloadFlag(!reloadFlag);

  //  setShouldScrollToTop(true); // Set to true when publishing
      // if (item?.isPublic === false) {
        scrollToTop()
    // Set to true when publishing
  // }


  };

  const cloneService = async (item) => {
    await cloneBusinessService(item?.serviceId);
    setReloadFlag(!reloadFlag);
  };

  const editService = (item) => {
    navigation.navigate("BusinessAddService", {
      serviceId: item?.serviceId,
      isEdit: true,
      setNewServiceCreated: setIsNewServiceCreated,
    });
  };

  const deleteService = async (item) => {
    console.log(item)
    await deleteBusinessService(item?.serviceId);
    setReloadFlag(!reloadFlag);
  };
console.log("checkData",businessHomeServiceArray.length )
console.log("checkData",businessHomeServiceArray )
  const renderHeader = () => (
    <View style={styles.header}>
      <TouchableOpacity style={styles.logoButton} onPress={choosePhoto}>

        <ProgressiveImage
          source={{ uri: businessProfile?.logoUrl || "", priority: FastImage.priority.high }}
          style={styles.logoView}
          resizeMode={FastImage.resizeMode.cover}
        />
        {!businessProfile?.logoUrl && (
          <View style={styles.cameraIcon}>
            <Image style={styles.cameraImage} source={images.cameraIcon} />
          </View>
        )}
      </TouchableOpacity>
      <EText
        style={styles.companyName}
        text={businessProfile?.companyName}
        fontType={FontType.gotham_regular}
        fontSize={20}
        fontWeight="500"
      />
      <EText
        style={styles.companyLocation}
        text={businessProfile?.town || businessProfile?.county}
        fontSize={15}
        fontWeight="500"
        fontType={FontType.gotham_regular}
        color={colors.textLightGray}
      />
      <AirbnbRating
        isDisabled
        showRating={false}
        defaultRating={businessProfile?.rating || 0}
        count={5}
        size={20}
        starContainerStyle={styles.rateStar}
      />
      <CompanyTabSection
        isServiceOnly
        currentTab={currentTab}
        setCurrentTab={setCurrentTab}
        serviceCount={totalServices}
      />

      <CustomButton
        text={t`add_new_service`}
        fgColor="white"
        bgColor={colors.darkGrayButton}
        style={styles.addPackagesServiceBtn}
        fSize={17}
        fontWeight="400"
        onClick={onPressAddNewService}
      />
    </View>
  );
  //This previous code
  // const renderServiceList = () => (
  //   <View style={styles.listContainer}>
  //   <FlatList
  //     ref={flatListRef}
  //     data={businessHomeServiceArray}
  //     keyExtractor={(item) => item?.serviceId?.toString()}
  //     initialNumToRender={10}
  //     maxToRenderPerBatch={10}
  //     windowSize={10}
  //     removeClippedSubviews={true}
  //     ListHeaderComponent={renderHeader} 
  //     ListHeaderComponentStyle={{backgroundColor:'white'}}// Move header content to FlatList
  //     renderItem={({ item, index }) => (
  //       <ServiceCard
  //         data={item}
  //         source="businessServiceList"
  //         currentIndex={index}
  //         onClonePress={() => showServiceActionPopup(2, item)}
  //         onEditPress={() => editService(item)}
  //         onPublishPress={() => showServiceActionPopup(1, item)}
  //         onDeletePress={() => showServiceActionPopup(3, item)}

  //       />

  //     )}
  //     ItemSeparatorComponent={() => <View style={styles.separator} />}
  //   />
  //   </View>
  // );
  const renderServiceList = () => (
    <View style={styles.listContainer}>
      <FlatList
       ref={flatListRef}
        data={businessHomeServiceArray}
        keyExtractor={(item, index) => `${item.serviceId}-${index}`}
        renderItem={({ item, index }) => <ServiceCard data={item} source="businessServiceList"
          currentIndex={index}
          onClonePress={() => showServiceActionPopup(2, item)}
          onEditPress={() => editService(item)}
          onPublishPress={() => showServiceActionPopup(1, item)}
          onDeletePress={() => showServiceActionPopup(3, item)} />}
        onEndReached={loadMoreServices}
        // onEndReachedThreshold={0.2}
        ListHeaderComponent={renderHeader}
        ListHeaderComponentStyle={{ backgroundColor: 'white' }}
        ListFooterComponent={isFetchingMore && <ActivityIndicator size="large" style={styles.loadingIndicator} />}
        ItemSeparatorComponent={() => <View style={styles.separator} />}
      />
      {/* {isLoading && <ActivityIndicator size="large" style={styles.loadingIndicator} />} */}
    </View>
  );
  const uploadImg = (file) =>
    cloudinaryImageUpload({
      upload_preset: "l4yg7wzl",
      folder: "app_business",
      file,
    });

  const chooseFile = (value) => {
    const picker = value === "camera" ? ImagePicker.openCamera : ImagePicker.openPicker;
    picker({ width: 300, height: 300, cropping: true }).then((img) => {
      setImage(img);
      setAlertOpen(false);
      setIsCamera(false);
      uploadImg(img);
    });
  };

  const cancelPhotoModal = () => {
    setAlertOpen(false);
    setIsCamera(false);
  };

  const choosePhoto = () => {
    setIsCamera(true);
    setAlertOpen(true);
  };

  return (
    <SafeAreaView style={styles.container}>
      {renderServiceList()}
      {alertOpen && (
        <CustomAlertComponent
          isCamera={isCamera}
          alertOpen={alertOpen}
          title="Thank You!"
          alertMessage="We have received your message. Someone from the Events6 team will contact you ASAP."
          onClick={cancelPhotoModal}
          onCloseModal={cancelPhotoModal}
          myCallBack={chooseFile}
        />
      )}
      {isLoading && <Loader />}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.white,
  },
  header: {
    alignItems: "center",
    marginTop: 16,
    bgColor: colors.white,
  },
  logoButton: {
    backgroundColor: colors.primaryGreyColor,
    borderRadius: 50,
    justifyContent: "center",
    alignItems: "center",
  },
  logoView: {
    height: 100,
    width: 100,
    borderRadius: 50,
    borderWidth: 1,
    borderColor: "#F0F0F0",
  },
  cameraIcon: {
    position: "absolute",
  },
  cameraImage: {
    height: 22,
    width: 30,
  },
  companyName: {
    marginTop: 10,
  },
  companyLocation: {
    marginTop: 5,
    height:23
  },
  rateStar: {
    marginTop: mvs(8),
    marginBottom: mvs(25),
  },
  addButtonContainer: {
    backgroundColor: "white",
  },
  addPackagesServiceBtn: {
    height: 45, // Make the button slimmer
    backgroundColor: colors.darkGrayButton,
    borderRadius: 20, // Slightly reduce the corner radius
    justifyContent: "center",
    alignItems: "center",
    marginTop: 20,
    marginHorizontal: 25, // Increase horizontal margin for better width control
    width: "70%", // Set button width to 90% of the screen for wider appearance
    alignSelf: "center", // Center the button horizontally
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  listContainer: {
    bgColor: colors.primaryGreyColor,
    flex: 1
  },
  separator: {
    height: mvs(12), // Add spacing between cards
    backgroundColor: colors.primaryGreyColor, // Red color for the gap between cards
  },
});

export default BusinessHomeScreen;
Editor is loading...
Leave a Comment