"use client";
import  React, { useState, useEffect } from 'react';
import { Fancybox } from '@fancyapps/ui'; 
import {handleFetchWithTokenRefresh} from '@utils/common';
import { useCookies } from 'react-cookie';
import PastWorkGalleryService, {PastWorkGalleryByHomeSection} from "@/service/PastWorkGalleryService";
import HomeSectionService from "@/service/HomeSectionService";
import Image from 'next/image';
import { useParams  } from "next/navigation";
import withAuth from "@/withAuth";
import routes from "@/routes";
import {RoleEnum, rowsPerPage} from '@constant/StaticData';
import Pagination from '@/components/PlanPortfolio/Pagination';

const GalleryPreview: React.FC = () => {
    const params = useParams<{ 'category': string }>();
    const [homeSectionTitle, setHomeSectionTitle] = useState<string | undefined>(undefined); 
    const [pastWorkGalleryDataByHomeSection, setPastWorkGalleryDataByHomeSection] = useState<PastWorkGalleryByHomeSection | undefined>(undefined); 
    const [cookies, setCookie, removeCookie] = useCookies();
    const [totalCount, setTotalCount] = useState<number>(0);
    const [totalPage, setTotalPage] = useState<number>(0);
    const [currentPage, setCurrentPage] = useState<number>(1);

    const fetchData = async () => {
        try {		
          const title = params['category'].replace(/-/g, '%');
          const homeSection = await HomeSectionService.getHomeSectionIdByTitle(title);
          setHomeSectionTitle(homeSection?.HouseSectionFind?.rows?.[0]?.title);
          const pastWorkGalleryDataByHomeSection = await PastWorkGalleryService.getPastWorkGalleryybyHomeSectionId(homeSection?.HouseSectionFind?.rows?.[0]?.id ?? 0, rowsPerPage, (currentPage-1)*rowsPerPage);
           if(pastWorkGalleryDataByHomeSection != undefined && pastWorkGalleryDataByHomeSection != null && pastWorkGalleryDataByHomeSection?.PastWorkGalleryFind){
            setPastWorkGalleryDataByHomeSection(pastWorkGalleryDataByHomeSection);
            setTotalCount(pastWorkGalleryDataByHomeSection?.PastWorkGalleryFind?.total);
            setTotalPage(pastWorkGalleryDataByHomeSection?.PastWorkGalleryFind?.pages);
          } 
        } catch (err:any) {
          console.error('Error during fetch data:', err);
          handleFetchWithTokenRefresh(err, cookies, setCookie, fetchData, "Error during fetch data");
        }
      };
    
      useEffect(() => {
        fetchData();
      },[currentPage]);

      const handlePageChange = (page: number) => {
        setCurrentPage(page);
      };

    useEffect(() => {
        Fancybox.bind("[data-fancybox='gallery']", {
          Carousel: {
            infinite: false,
          },
        });
        return () => {
            Fancybox.destroy();
          };
      }, []);
    return (
        <>
          <main className="bg-secondary bg-secondary d-flex justify-content-center align-items-center">
            <section className='gallery-preview'>
                <div className="container-xl container-fluid">
                    <div className="row mt-5">
                        <div className="col-12">
                            <h1 className="mb-5 style-category-text text-uppercase">{homeSectionTitle}</h1>
                        </div>
                        {pastWorkGalleryDataByHomeSection?.PastWorkGalleryFind?.rows && pastWorkGalleryDataByHomeSection.PastWorkGalleryFind.rows.length > 0 ? (
                        pastWorkGalleryDataByHomeSection.PastWorkGalleryFind.rows.map((row) => {
                            const imageUrl = row?.file_image_url?.direct;
                            const validImageUrl = imageUrl && imageUrl.startsWith('http') ? imageUrl : '/Images/Property-3.jpg';
                            return(
                                <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-6 col-sm-6 col-12" key={row.id}>
                                    <div className="card border-0 mb-4">
                                        <div className="card-image position-relative">
                                            <a
                                                href={validImageUrl}
                                                className="img-header"
                                                data-fancybox="gallery"
                                                data-caption="Caption Images 1"
                                            >
                                                <Image
                                                src={validImageUrl}
                                                alt="gallery-category-images"
                                                className="img-fluid gallery-category-images"
                                                width={420}
                                                height={280}
                                                />
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            );
                        })
                        ) : null}

                    </div>
                    <Pagination totalPages={totalPage} currentPage={currentPage} onPageChange={handlePageChange} totalCount={totalCount}/>
                </div>
            </section>
           </main>

        </>
    );
};

//export default GalleryPreview;
export default withAuth(GalleryPreview, routes.galleries.auth, RoleEnum.CUSTOMER);