"use client";
import FilterSidebar from '@/components/PlanPortfolio/FilterSidebar';
import MobileFilterSidebar from '@/components/PlanPortfolio/MobileFilterSidebar';
import FloorPlanService, {FloorplanOPData, Filters} from "@/service/FloorPlanService";
import React, { useState, useEffect } from "react";
import {handleFetchWithTokenRefresh} from '@utils/common';
import { useCookies } from 'react-cookie';
import {SortData, rowsPerPage, sortField, sortOrder} from '@constant/StaticData';
import Listing from '@/components/PlanPortfolio/Listing';
import Pagination from '@/components/PlanPortfolio/Pagination';
import withAuth from "@/withAuth";
import routes from "@/routes";
import {RoleEnum} from '@constant/StaticData';
import SearchLogic from '@/components/PlanPortfolio/SearchLogic';

const PlanPortfolio: React.FC = () => {
    const [FloorPlanData, setFloorPlanData] = useState<FloorplanOPData | undefined>(undefined); 
    const [cookies, setCookie, removeCookie] = useCookies();
    const [isExpanded, setIsExpanded] = useState<boolean>(false);
    const [totalCount, setTotalCount] = useState<number>(0);
    const [totalPage, setTotalPage] = useState<number>(0);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [selectedSortField, setSelectedSortField] = useState<string>(sortField);
    const [selectedSortOrder, setSelectedSortOrder] = useState<string>(sortOrder);
    const {        
        handleInputChange,
    } = SearchLogic();

    const [filters, setFilters] = useState<Filters>({
        floorPlan:'',
        sqftMin: '',
        sqftMax: '',
        beds: [],
        baths: [],
        garage: [],
        garage_type: [],
        rooms: [],
        features: [],
        architectureStyles: [],
        pageSize: rowsPerPage,  
        start: (currentPage-1)*rowsPerPage,      
        field: selectedSortField, 
        sort: selectedSortOrder,   
      });
       
      useEffect(() => {
        
        handleSearch();
      },[currentPage, selectedSortField, selectedSortOrder]);

      const toggleMobSidebar = (): void => {
        setIsExpanded(prevState => !prevState);
    };

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

    const handleSortChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const value = e.target.value;
        const [sortField, sortOrder] = value.split('|');
        setSelectedSortField(sortField);
        setSelectedSortOrder(sortOrder);
        setCurrentPage(1);
    };

    const onFloorPlanSearch = (e: React.ChangeEvent<HTMLInputElement>)  => {
        const value = e.target.value;
        filters.floorPlan = value;
        
        handleSearch();
      };

    const handleSearch = async() => {
        filters.start = (currentPage-1)*rowsPerPage;
        filters.field = selectedSortField;
        filters.sort = selectedSortOrder;
        
        try {
            
            const FloorPlanData = await FloorPlanService.getFloorplanWithFilter(filters);
            
            if(FloorPlanData != undefined && FloorPlanData != null && FloorPlanData?.FloorPlanFind){
                setFloorPlanData(FloorPlanData);
                setTotalCount(FloorPlanData?.FloorPlanFind?.total);
                setTotalPage(FloorPlanData?.FloorPlanFind?.pages);
            }  
        }
        catch (err:any) {
            console.error('Error during fetch data:', err);
            handleFetchWithTokenRefresh(err, cookies, setCookie, handleSearch, "Error during fetch data");
          }
    };
    
    return (
        <>
           <section className="main-section d-flex bg-secondary">
                <FilterSidebar setFilters={setFilters} handleSearch={handleSearch} selectedSortField={selectedSortField} selectedSortOrder={selectedSortOrder} setCurrentPage={setCurrentPage}/>
                <main className="w-100 p-md-3">
                    <div className="container-fluid mt-3">
                        <div className="row">
                            <div className="col-12">
                                <div className="responsive-header-area">

                                    <div className="search-area d-lg-none d-sm-flex">
                                        <div className="input-group mb-3">
                                            <input type="text" className="form-control rounded-pill search-input" name="floorPlan" onChange={handleInputChange('floorPlan')} 
                                                onBlur={onFloorPlanSearch} placeholder="Search" aria-label="Recipient's username"
                                                aria-describedby="basic-addon2"/>

                                        </div>
                                    </div>
                                    <div className="grid-head-area d-lg-none d-sm-flex justify-content-between mb-4">
                                       
                                        <h3 className="text-primary d-sm-flex d-none">
                                            {totalCount} Plans
                                        </h3>
                                        <div className="d-flex align-items-center">
                                            <button
                                                className="btn filter-btn me-3 text-primary d-flex justify-content-center align-items-center"
                                                type="button" onClick={toggleMobSidebar} 
                                                aria-controls="offcanvasRight">
                                                <span className="me-2 d-flex">
                                                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"
                                                        xmlns="http://www.w3.org/2000/svg">
                                                        <path
                                                            d="M1.66667 1H12.3333C12.5101 1 12.6797 1.07024 12.8047 1.19526C12.9298 1.32029 13 1.48986 13 1.66667V2.724C13 2.9008 12.9297 3.07034 12.8047 3.19533L8.52867 7.47133C8.40363 7.59633 8.33337 7.76587 8.33333 7.94267V12.146C8.33333 12.2473 8.31023 12.3473 8.26578 12.4384C8.22133 12.5295 8.1567 12.6092 8.07681 12.6716C7.99692 12.7339 7.90387 12.7772 7.80473 12.7982C7.70559 12.8192 7.60297 12.8173 7.50467 12.7927L6.17133 12.4593C6.02717 12.4232 5.89921 12.34 5.80777 12.2228C5.71634 12.1056 5.66667 11.9613 5.66667 11.8127V7.94267C5.66663 7.76587 5.59637 7.59633 5.47133 7.47133L1.19533 3.19533C1.0703 3.07034 1.00004 2.9008 1 2.724V1.66667C1 1.48986 1.07024 1.32029 1.19526 1.19526C1.32029 1.07024 1.48986 1 1.66667 1Z"
                                                            stroke="#2B2B27" strokeLinecap="round" strokeLinejoin="round" />
                                                    </svg>
                                                </span>
                                                Filters
                                            </button>
                                            <select className="form-select sort-select mb-0 "
                                                aria-label="Default select example" onChange={handleSortChange} value={`${selectedSortField}|${selectedSortOrder}`}>
                                                <option className="bg-white text-uppercase" selected>Sort</option>
                                                {Object.entries(SortData).map(([key, label]) => (
                                                    <option className="bg-white" value={key} key={key}>{label}</option>
                                                ))}
                                            </select>

                                        </div>

                                        <h3 className="text-primary d-sm-none d-block">
                                            {totalCount} Plans
                                        </h3>
                                    </div>
                                </div>
                                <div className="grid-head-area d-lg-flex d-none justify-content-between mb-4">
                                    <div className="d-flex align-items-center">

                                        <h3 className="text-primary">
                                            {totalCount} Plans
                                        </h3>
                                    </div>
                                    <div className="d-flex align-items-center">
                                        <select className="form-select w-100 sortopt-text bg-white mb-0 text-uppercase"
                                            aria-label="Default select example" onChange={handleSortChange}  value={`${selectedSortField}|${selectedSortOrder}`}>
                                            <option className="bg-white text-uppercase text-primary" selected>Sort</option>
                                            {Object.entries(SortData).map(([key, label]) => (
                                                <option className="bg-white text-uppercase" value={key} key={key}>{label}</option>
                                            ))}
                                        </select>

                                    </div>
                                </div>
                                <Listing  data={FloorPlanData}/>
                                <Pagination totalPages={totalPage} currentPage={currentPage} onPageChange={handlePageChange} totalCount={totalCount}/>
                            </div>
                        </div>
                    </div>
                    <MobileFilterSidebar isExpanded={isExpanded} setIsExpanded={setIsExpanded} setFilters={setFilters} handleSearch={handleSearch} selectedSortField={selectedSortField} selectedSortOrder={selectedSortOrder} setCurrentPage={setCurrentPage}/>
                </main>
            </section>

        </>
    );
};
//export default PlanPortfolio;
export default withAuth(PlanPortfolio, routes.planportfolio.auth, RoleEnum.CUSTOMER);