"use client";
/* @author: Hemal
  File: FindAHomeMain.tsx
  Description: This file contains the FindAHomeMain component, which is the main section of the Find a Home page.
  It fetches the property list from the Redux store and maps it to the FindHomeCard component.
  It also handles filtering and sorting options.
  */
import { AppDispatch, RootState } from "@/redux/slices";
import { propertyActions } from "@/redux/slices/Property/property";
import getPropertyList from "@/redux/thunks/Property/property.thunk";
import styles from "@/src/app/(lang)/(pages)/find-a-home/page.module.scss";
import { PropertyData } from "@/src/types/api/property.type";
import { FindAHomeContent as FindAHomeContents } from "@/src/types/StaticContent/findahome.content.type";
import useIsClient from "@/src/utils/customHooks/useIsClient";
import Routes from "@/src/utils/RouteConstants";
import { PropertyCard, SearchbarMain, SearchPlaceMap } from "blankbase-packages";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import LoaderSection from "../../LoaderSection";
import NoPropertyDataListing from "../../NoPropertyDataListing/NoPropertyDataListing";
import apiClient from "@/src/interceptor/apiClient";

const FindAHomeMain: React.FC<{ FindAHomeContent: FindAHomeContents, BASE_URL: string }> = ({ FindAHomeContent, BASE_URL }) => {

  const isClient = useIsClient();
  const router = useRouter();
  const searchParams = useSearchParams();
  // Get the full query string from the URL
  const fullQueryString = searchParams.toString();
  // Initialize the dispatch function
  const dispatch = useDispatch<AppDispatch>();
  const { allProperties, propertyMeta, filterListMeta, isLoading, isPageLoading, currentPage } = useSelector((state: RootState) => state.property);
  const { PropertyView } = useSelector((state: RootState) => state.common);
  const [view, setView] = useState("list");
  const [apiPayload, setApiPayload] = useState(null);
  const [isSticky, setIsSticky] = useState(false);

  useEffect(() => {
    // Scroll to top with smooth behavior when `view` changes
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [PropertyView]);

  // Pagination when scrolling to bottom of the page
  useEffect(() => {
    /**
   * Handles scroll event for the scroll pagination of property list
   * Get the current scroll position of the page
   * @param value - The Increment value of page state when scroll height reached 70% or more
   */
    const handleScroll = () => {
      const scrollTop = window.scrollY;
      const windowHeight = window.innerHeight;
      const fullHeight = document.documentElement.scrollHeight;
      const scrolledToBottom = (scrollTop + windowHeight) / fullHeight >= 0.7;
      //@ts-ignore
      const hasMoreData = propertyMeta && allProperties.length < propertyMeta.totalCount;
      if (scrolledToBottom && !isLoading && hasMoreData) {
        dispatch(propertyActions.successCurrentPage(currentPage + 1));
      }
    };

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [isLoading, allProperties.length, propertyMeta]);

  useEffect(() => {
    /**
     * Handles scroll event for the scroll pagination of property list
     * Get the current scroll position of the page
     * @param value - The Increment value of page state when scroll height reached 70% or more
     */
    const handleScroll = () => {
      const scrollTop = window.scrollY
      if (scrollTop > 40) {
        setIsSticky(true);
      } else {
        setIsSticky(false);
      }
    }

    window.addEventListener('scroll', handleScroll)
    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [])

  useEffect(() => {
    return () => {
      dispatch(propertyActions.resetPropertyListState())
    }
  }, [])


  /**
   * Fetches the property list from the Redux store by dispatching the getPropertyList action creator
   * @param payload The payload to be passed to the getPropertyList action creator
   */
  const fetchPropertyList = (payload: any) => {
    let finalPayload = payload;
    if(view === 'map') {
      finalPayload = {
        ...payload, 
        perPage: -1,
        page: 1
      }
    }
    dispatch(getPropertyList(finalPayload))
  }

  useEffect(() => {
    if (apiPayload) {
      if (currentPage === 1) {
        fetchPropertyList(apiPayload)
      } else {
        if (apiPayload?.priceEnd) {
          if (apiPayload?.countOnly) {
            fetchPropertyList(apiPayload)
          } else {
            dispatch(propertyActions.successCurrentPage(1));
            window.scrollTo({ top: 0, behavior: 'instant' });
          }
        } else {
          const { page, ...rest } = apiPayload
          fetchPropertyList({ page: currentPage, ...rest })
        }
      }
    }
  }, [apiPayload, currentPage, view])

  /**
   * Handles click event on info window of Google Map
   * @param item Object containing the property data
   * @returns void
   */
  const onInfoWindowClick = (item: any) => {
    router.push(`${Routes.FIND_A_HOME_INFO(item?.slug)}?${fullQueryString}`);
  }

  /**
   * Navigates to the Find A Home Info page for the selected property.
   * Constructs the URL using the item slug and current query string.
   * 
   * @param item - The property data object containing at least the slug.
   */
  const onCardClick = (item: any) => {
    router.push(`${Routes.FIND_A_HOME_INFO(item?.slug)}?${fullQueryString}`);
  };

  return (
    <section className={`${styles.FilterAndResultWrap}`}>
      <div className={`container`}>
        {isClient &&
          <SearchbarMain
            view={view}
            setView={setView}
            propertyMeta={filterListMeta}
            setApiPayload={setApiPayload}
            isDashboard={false}
            userType={'guest'}
            currency={'USD'}
            BASE_URL={BASE_URL}
            isSticky={isSticky}
            apiClient={apiClient}
          />
        }
        {view === 'list' ?
          <>
            {isPageLoading ?
              <LoaderSection /> :
              allProperties?.length === 0 ?
                <NoPropertyDataListing NoPropertyListingContent={FindAHomeContent?.NO_PROPERTY_DATA_LISTING} />
                :
                <div
                  className={`${styles.findHomeCardWrapper} lg:pt-[0px] relative grid grid-cols-1 lg:grid-cols-2 gap-5 xl:gap-8 xxxl:gap-10 w-full`}
                >
                  {allProperties?.map((item: PropertyData, cardKey: number) => {
                    return (
                      <React.Fragment key={cardKey}>
                        <PropertyCard
                          item={item}
                          isHostCard={false}
                          propertyImages={[item?.workspaceImage, ...(item?.propertyImage || [])]}
                          onCardClick={onCardClick}
                        />
                      </React.Fragment>
                    )
                  }
                  )}
                </div>
            }
          </>
          :
          <div className={`max-w-[100%] mx-auto`}>
            <SearchPlaceMap
              propertyList={allProperties}
              onInfoWindowClick={onInfoWindowClick}
              GOOGLE_MAPS_API_KEY={process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}
            />
          </div>
        }
      </div>
    </section>
  );
};

export default FindAHomeMain;
