import { useState, useEffect } from 'react';
import RoomTypeService, {RoomTypeOPData} from "@/service/RoomTypesService";
import FeaturesService, {FeaturesOPData} from "@/service/FeaturesService";
import ArchitectureStyleService, {ArchitectureStyleOPData} from "@/service/ArchitectureStyleService";
import {BedsData, BathsData, GarageData, rowsPerPage} from '@constant/StaticData';
import SearchLogic from '@/components/PlanPortfolio/SearchLogic';
import FloorPlanService, {Filters} from "@/service/FloorPlanService";
import {handleFetchWithTokenRefresh} from '@utils/common';
import { useCookies } from 'react-cookie';
import SearchIcon from '@mui/icons-material/Search';

interface FilterSidebarProps {
    setFilters: React.Dispatch<React.SetStateAction<Filters>>;
    handleSearch: () => void;
    selectedSortField: string;
    selectedSortOrder: string;
    setCurrentPage: React.Dispatch<React.SetStateAction<number>>;
}

const FilterSidebar: React.FC<FilterSidebarProps> = ({setFilters, handleSearch, selectedSortField, selectedSortOrder, setCurrentPage }) => {
    const [isExpanded, setIsExpanded] = useState<boolean>(false);
    const [roomTypeData, setRoomTypeData] = useState<RoomTypeOPData | undefined>(undefined); 
    const [featuresData, setFeaturesData] = useState<FeaturesOPData | undefined>(undefined); 
    const [architectureStyleData, setArchitectureStyleData] = useState<ArchitectureStyleOPData | undefined>(undefined); 
    const [cookies, setCookie, removeCookie] = useCookies();
    const {
        filters,
        handleInputChange,
        handleCheckboxChange,
        handleClearFilters
    } = SearchLogic();
    const [isUpdate, setIsUpdate] = useState<boolean>(false);

    useEffect(() => {
        const handleResize = () => {
            const sidebarCollapse = document.querySelector('.sidebar-collapse') as HTMLElement;
            const filterCollapseBtn = document.querySelector('.filter-collapse-btn-block') as HTMLElement;

            if (window.innerWidth <= 1200 && isExpanded) {
                sidebarCollapse.style.width = '45%';
                filterCollapseBtn.style.right = '-8%';
            } else if (isExpanded) {
                sidebarCollapse.style.width = '25%';
                filterCollapseBtn.style.right = '-6%';
            } else {
                sidebarCollapse.style.width = '1%';
                filterCollapseBtn.style.right = '-148%';
            }
        };

        handleResize(); 
        window.addEventListener('resize', handleResize); 

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, [isExpanded]); 

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

    const fetchRoomType = async () => {
        try {
            const roomTypes = await RoomTypeService.getRoomTypes();
            if(roomTypes && roomTypes?.RoomTypeFind){
            setRoomTypeData(roomTypes);
            }
        }
        catch (err:any) {
            console.error('Error during fetch data:', err);
            handleFetchWithTokenRefresh(err, cookies, setCookie, fetchRoomType, "Error during fetch data");
          }
      }
      const fetchFeatures = async () => {
        try {
            const features = await FeaturesService.getAllFeatures();
            if(features && features?.FeaturesFind){
            setFeaturesData(features);
            }
        }
        catch (err:any) {
            console.error('Error during fetch data:', err);
            handleFetchWithTokenRefresh(err, cookies, setCookie, fetchFeatures, "Error during fetch data");
        }
      }
      const fetchArchitectureStyle = async () => {
        try {
            const architectureStyle = await ArchitectureStyleService.getAllArchitectureStyle();
            if(architectureStyle && architectureStyle?.ArchitectureStyleFind){
                setArchitectureStyleData(architectureStyle);
            }
        }
        catch (err:any) {
            console.error('Error during fetch data:', err);
            handleFetchWithTokenRefresh(err, cookies, setCookie, fetchArchitectureStyle, "Error during fetch data");
        }
      }
    
      useEffect(() => {
        fetchRoomType();
        fetchFeatures();
        fetchArchitectureStyle();
      },[]);

      const getUpdatedFilters = (): Filters => ({
        floorPlan:filters.floorPlan,
        sqftMin: filters.sqftMin,
        sqftMax: filters.sqftMax,
        beds: filters.beds,
        baths: filters.baths,
        garage: filters.garage,
        rooms: filters.rooms,
        features: filters.features,
        architectureStyles: filters.architectureStyles,
        pageSize: rowsPerPage,  
        start: 0,               
        field: selectedSortField,            
        sort: selectedSortOrder, 
        garage_type: filters.garage_type         
      });

      useEffect(() => {
        const updatedFilters = getUpdatedFilters();
        setFilters( updatedFilters); 
      }, [filters, setFilters]);

      const onApplyFilters = () => {
        const updatedFilters = getUpdatedFilters();
        setFilters( updatedFilters); 
        setCurrentPage(1);
        setIsUpdate(false);
        handleSearch();
      };

      const onClearFilters = () => {
        handleClearFilters();

        setFilters({
            floorPlan: "",
            sqftMin: "",
            sqftMax: "",
            beds: [],
            baths: [],
            garage: [],
            rooms: [],
            features: [],
            architectureStyles: [],
            pageSize: rowsPerPage,
            start: 0,
            field: selectedSortField,
            sort: selectedSortOrder,
            garage_type: [],

        });
        setCurrentPage(1);
        setIsUpdate(true);
      };

      useEffect(() => {
        handleSearch();
      }, [isUpdate]);

      console.log(filters);
      
    return (
        <>
            <div className="d-lg-flex d-none bg-transparent sidebar-collapse position-relative">
                <div className={`collapse filter-collapse w-100 bg-primary sidebar-collapse ${isExpanded ? 'show' : ''}`} id="collapseExample" style={{letterSpacing:1.1}}>
                    <aside className="filter-sidebar w-100  p-3 mt-3">
                        <div className="search-area mb-4">
                        <h6 style={{ fontFamily: 'Montserrat, serif' }}>SEARCH</h6>
                            <div className="input-group mb-3">
                            {/* <SearchIcon className="input-icon" /> */}
                                <input type="text" className="form-control rounded-pill search-input position-relative bg-primary" placeholder="SEARCH" name="floorPlan"
                                    aria-label="Recipient's username" aria-describedby="basic-addon2" onChange={handleInputChange('floorPlan')} value={filters.floorPlan}/>
                           <div className="input-icon-container">
                               
                            </div>
                            </div>
                        </div>

                    <div className="filters-container bg-primary" style={{ fontFamily: 'Montserrat, serif'}}>
                    
                    {/* Other fixed sections can remain outside scroll */}
                    <div className="filter-section mb-3">
                        <h6 className="text-white text-uppercase ">Square Footage</h6>
                        <div className="sqft-area d-flex justify-content-between">
                        <input 
                            className="form-control rounded-pill w-50 border-white bg-transparent text-white text-uppercase" 
                            type="text" 
                            name="sqftMin" 
                            placeholder="Min" 
                            aria-label="default input example" 
                            onChange={handleInputChange('sqftMin')} 
                            value={filters.sqftMin}
                        />
                        &nbsp; - &nbsp;
                        <input 
                            className="form-control rounded-pill w-50 border-white bg-transparent text-white text-uppercase" 
                            type="text" 
                            name="sqftMax" 
                            placeholder="Max" 
                            aria-label="default input example" 
                            onChange={handleInputChange('sqftMax')} 
                            value={filters.sqftMax}
                            style={{ borderColor: 'white',color:'white' }}
                        />
                        </div>
                    </div>

                    {/* Add a scrollable container for filters from "Beds" to "Architectural Style" */}
                    <div className="scrollable-filters-container" style={{ maxHeight: '500px', overflowY: 'auto' }}>
                        
                        {/* Beds Section */}
                        <div className="filter-section mb-3">
                        <h6 className="text-white text-uppercase" >Bed</h6>
                        <div className=" ms-2" style={{ display: 'flex', flexDirection: 'column' ,}}>
                            {Object.entries(BedsData).map(([key, label]) => (
                            <div className="form-check mb-2" key={key}>
                                <input 
                                className="form-check-input my-1 me-1" 
                                type="checkbox" 
                                id={`bedCheckbox${key}`}
                                value={key} 
                                name="beds" 
                                onChange={handleCheckboxChange('beds')} 
                                checked={filters.beds.includes(key)} 
                                />
                                <label className="form-check-label text-white text-uppercase" htmlFor={`bedCheckbox${key}`} >
                                {label}
                                </label>
                            </div>
                            ))}
                        </div>
                        </div>



                        {/* Baths Section */}
                        <div className="filter-section mb-3" style={{alignItems:"center"}}>
                        <h6 className="text-white text-uppercase" >Bath</h6>
                        <div className="baths-area ms-2" style={{ display: 'flex', flexDirection: 'column' }}>
                            {Object.entries(BathsData).map(([key, label]) => (
                            <div className="form-check" key={key}>
                                <input 
                                className="form-check-input my-1 me-1" 
                                type="checkbox" 
                                id={`bathCheckbox${key}`}
                                value={key} 
                                name="baths" 
                                onChange={handleCheckboxChange('baths')} 
                                checked={filters.baths.includes(key)} 
                                />
                                <label className="form-check-label text-white text-uppercase" htmlFor={`bathCheckbox${key}`} >
                                {label}
                                </label>
                            </div>
                            ))}
                        </div>
                        </div>

                        {/* Garage Section */}
                        <div className="filter-section mb-4">
                        <h6 className="text-white text-uppercase" >Garage</h6>
                        <div className="garage-area ms-2" style={{ display: 'flex', flexDirection: 'column' }}>
                            {Object.entries(GarageData).map(([key, label]) => (
                            <div className="form-check mb-2" key={key}>
                                <input 
                                className="form-check-input my-1 me-1" 
                                type="checkbox" 
                                id={`garageCheckbox${key}`}
                                value={key} 
                                name="garage_type" 
                                onChange={handleCheckboxChange('garage_type')} 
                                checked={filters.garage_type.includes(key)} 
                                />
                                <label className="form-check-label text-white text-uppercase" htmlFor={`garageCheckbox${key}`} >
                                {label}
                                </label>
                            </div>
                            ))}
                        </div>
                        </div>

                        {/* Rooms Section */}
                        <div className="filter-section mb-4">
                        <h6 className="text-white text-uppercase" >Rooms</h6>
                        <div className="rooms-area">
                            {roomTypeData?.RoomTypeFind?.rows && roomTypeData.RoomTypeFind.rows.length > 0 && (
                            roomTypeData.RoomTypeFind.rows.map((row, index) => (
                                <div className="form-check ms-2" key={index}>
                                <input 
                                    className="form-check-input " 
                                    type="checkbox" 
                                    value={row.id} 
                                    id={`flexCheckDefault${index}`} 
                                    name="rooms" 
                                    onChange={handleCheckboxChange('rooms')} 
                                    checked={filters.rooms.includes(`${row.id}`)} 
                                />
                                <label className="form-check-label ms-2 text-white text-uppercase" htmlFor={`flexCheckDefault${index}`}>
                                    {row.title}
                                </label>
                                </div>
                            ))
                            )}
                        </div>
                        </div>

                        {/* Features Section */}
                        <div className="filter-section mb-4">
                        <h6 className="text-white text-uppercase" >Features</h6>
                        <div className="features-area">
                            {featuresData?.FeaturesFind?.rows && featuresData.FeaturesFind.rows.length > 0 && (
                            featuresData.FeaturesFind.rows.map((row, index) => (
                                <div className="form-check ms-2" key={index}>
                                <input 
                                    className="form-check-input" 
                                    type="checkbox" 
                                    value={row.id} 
                                    id={`flexCheckDefault${index}`} 
                                    name="features" 
                                    onChange={handleCheckboxChange('features')} 
                                    checked={filters.features.includes(`${row.id}`)} 
                                />
                                <label className="form-check-label ms-2 text-white text-uppercase" htmlFor={`flexCheckDefault${index}`}>
                                    {row.title}
                                </label>
                                </div>
                            ))
                            )}
                        </div>
                        </div>

                        {/* Architectural Style Section */}
                        <div className="filter-section mb-3">
                        <h6 className="text-white text-uppercase" >Architectural Style</h6>
                        <div className="architecture-style-area">
                            {architectureStyleData?.ArchitectureStyleFind?.rows && architectureStyleData.ArchitectureStyleFind.rows.length > 0 && (
                            architectureStyleData.ArchitectureStyleFind.rows.map((row, index) => (
                                <div className="form-check ms-2" key={index}>
                                <input 
                                    className="form-check-input" 
                                    type="checkbox" 
                                    value={row.id} 
                                    id={`flexCheckDefault${index}`} 
                                    name="architectureStyles" 
                                    onChange={handleCheckboxChange('architectureStyles')} 
                                    checked={filters.architectureStyles.includes(`${row.id}`)} 
                                />
                                <label className="form-check-label ms-2 text-white text-uppercase" htmlFor={`flexCheckDefault${index}`} >
                                    {row.title}
                                </label>
                                </div>
                            ))
                            )}
                        </div>
                        </div>
                    </div>

                    {/* Apply and Clear buttons */}
                    <div className="btns-block m-5">
                        <button 
                        type="button" 
                        className="btn bg-transparent border-white text-white rounded-pill mr-2" 
                        onClick={onApplyFilters} 
                        style={{ textTransform: 'uppercase', }}
                        >
                        Search
                        </button>
                        <button 
                        type="button" 
                        className="btn bg-transparent border-white text-white rounded-pill" 
                        onClick={onClearFilters} 
                        style={{ textTransform: 'uppercase' }}
                        >
                        Clear
                        </button>
                    </div>
                    </div>


                        {/* <div className="accordion" id="accordionExample">
                            <div className="accordion-item mb-3 border-top-0 border-left-0 border-right-0 bg-primary">
                                <h2 className="accordion-header text-primary" id="headingOne">
                                    <button className="accordion-button px-1" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                        Square Footage
                                    </button>
                                </h2>
                                <div id="collapseOne" className="accordion-collapse collapse show" aria-labelledby="headingOne"
                                    data-bs-parent="#accordionExample">
                                    <div className="accordion-body  py-1 px-1">
                                        <div className="sqft-area d-flex justify-content-between">
                                            <div className="sqft-area d-flex justify-content-between">
                                                <input className="form-control rounded-pill w-50 bg-primary" type="text" name='sqftMin'
                                                    placeholder="Min" aria-label="default input example" onChange={handleInputChange('sqftMin')} value={filters.sqftMin}/>
                                                &nbsp; - &nbsp;
                                                <input className="form-control rounded-pill w-50 bg-primary" type="text" name='sqftMax'
                                                    placeholder="Max" aria-label="default input example" onChange={handleInputChange('sqftMax')} value={filters.sqftMax}/>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="accordion-item mb-3 border-top-0 border-left-0 border-right-0 bg-primary">
                                <h2 className="accordion-header text-primary" id="headingTwo">
                                    <button className="accordion-button px-1 collapsed" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                                        Beds
                                    </button>
                                </h2>
                                <div id="collapseTwo" className="accordion-collapse collapse" aria-labelledby="headingTwo"
                                    data-bs-parent="#accordionExample">
                                    <div className="accordion-body beds-area py-1 px-1">
                                    {Object.entries(BedsData).map(([key, label]) => (
                                        <div className="form-check form-check-inline me-4" key={key}>
                                            <input className="form-check-input my-0 me-2" type="checkbox" id={`bedCheckbox${key}`}
                                                value={key} name="beds" onChange={handleCheckboxChange('beds')} checked={filters.beds.includes(key)}/>
                                            <label className="form-check-label text-white" htmlFor={`bedCheckbox${key}`}>{label}</label>
                                        </div>
                                    ))}
                                    </div>
                                </div>
                            </div>
                            <div className="accordion-item mb-3 border-top-0 border-left-0 border-right-0 bg-primary">
                                <h2 className="accordion-header text-primary" id="headingThree">
                                    <button className="accordion-button px-1 collapsed" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                                        Baths
                                    </button>
                                </h2>
                                <div id="collapseThree" className="accordion-collapse collapse" aria-labelledby="headingThree"
                                    data-bs-parent="#accordionExample">
                                    <div className="accordion-body beds-area py-1 px-1">
                                    {Object.entries(BathsData).map(([key, label]) => (
                                        <div className="form-check form-check-inline me-4" key={key}>
                                            <input className="form-check-input my-0 me-2" type="checkbox" id={`bathCheckbox${key}`}
                                                value={key} name="baths" onChange={handleCheckboxChange('baths')} checked={filters.baths.includes(key)}/>
                                            <label className="form-check-label text-white" htmlFor={`bathCheckbox${key}`}>{label}</label>
                                        </div>
                                    ))}
                                    </div>
                                </div>
                            </div>
                            <div className="accordion-item mb-3 border-top-0 border-left-0 border-right-0 bg-primary">
                                <h2 className="accordion-header text-primary" id="headingFour">
                                    <button className="accordion-button px-1 collapsed" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour">
                                        Garage
                                    </button>
                                </h2>
                                <div id="collapseFour" className="accordion-collapse collapse" aria-labelledby="headingFour"
                                    data-bs-parent="#accordionExample">
                                    <div className="accordion-body beds-area py-1 px-1">
                                        {Object.entries(GarageData).map(([key, label]) => (
                                            <div className="form-check form-check-inline me-4" key={key}>
                                                <input className="form-check-input my-0 me-2" type="checkbox" id={`garageCheckbox${key}`}
                                                    value={key} name="garage" onChange={handleCheckboxChange('garage')} checked={filters.garage.includes(key)}/>
                                                <label className="form-check-label text-white" htmlFor={`garageCheckbox${key}`}>{label}</label>
                                            </div>
                                        ))}

                                    </div>
                                </div>
                            </div>
                            <div className="accordion-item mb-3 border-top-0 border-left-0 border-right-0 bg-primary">
                                <h2 className="accordion-header text-primary" id="headingFive">
                                    <button className="accordion-button px-1 collapsed" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseFive" aria-expanded="false" aria-controls="collapseFive">
                                        Rooms
                                    </button>
                                </h2>
                                <div id="collapseFive" className="accordion-collapse collapse" aria-labelledby="headingFive"
                                    data-bs-parent="#accordionExample">
                                    <div className="accordion-body beds-area py-1 px-1 scrollable custom-scroll-container">
                                        {roomTypeData?.RoomTypeFind?.rows && roomTypeData.RoomTypeFind.rows.length > 0 && (
                                            roomTypeData.RoomTypeFind.rows.map((row, index) => (
                                                <div className="form-check ms-2" key={index}>
                                                    <input className="form-check-input" type="checkbox" value={row.id} id={`flexCheckDefault${index}`} name="rooms" 
                                                    onChange={handleCheckboxChange('rooms')} checked={filters.rooms.includes(`${row.id}`)}/>
                                                    <label className="form-check-label ms-2 text-white" htmlFor={`flexCheckDefault${index}`}>
                                                        {row.title}
                                                    </label>
                                                </div>
                                            ))
                                        )}
                                    </div>
                                </div>
                            </div>
                            <div className="accordion-item mb-3 border-top-0 border-left-0 border-right-0 bg-primary">
                                <h2 className="accordion-header text-primary" id="headingSix">
                                    <button className="accordion-button px-1 collapsed" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseSix" aria-expanded="false" aria-controls="collapseSix">
                                        Features
                                    </button>
                                </h2>
                                <div id="collapseSix" className="accordion-collapse collapse" aria-labelledby="headingSix"
                                    data-bs-parent="#accordionExample">
                                    <div className="accordion-body beds-area py-1 px-1 scrollable custom-scroll-container">
                                        {featuresData?.FeaturesFind?.rows && featuresData.FeaturesFind.rows.length > 0 && (
                                            featuresData.FeaturesFind.rows.map((row, index) => (
                                                <div className="form-check ms-2" key={index}>
                                                <input className="form-check-input" type="checkbox" value={row.id} id={`flexCheckDefault${index}`} name="features" 
                                                onChange={handleCheckboxChange('features')} checked={filters.features.includes(`${row.id}`)}/>
                                                <label className="form-check-label ms-2 text-white" htmlFor={`flexCheckDefault${index}`}>
                                                    {row.title}
                                                </label>
                                            </div>
                                            ))
                                        )}
                                        
                                    </div>
                                </div>
                            </div>
                            <div className="accordion-item mb-3 border-top-0 border-left-0 border-right-0 bg-primary">
                                <h2 className="accordion-header text-primary" id="headingSeven">
                                    <button className="accordion-button px-1 collapsed" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseSeven" aria-expanded="false" aria-controls="collapseSeven">
                                        Architectural Style
                                    </button>
                                </h2>
                                <div id="collapseSeven" className="accordion-collapse collapse" aria-labelledby="headingSeven"
                                    data-bs-parent="#accordionExample">
                                    <div className="accordion-body beds-area py-1 px-1 scrollable custom-scroll-container">
                                        {architectureStyleData?.ArchitectureStyleFind?.rows && architectureStyleData.ArchitectureStyleFind.rows.length > 0 && (
                                            architectureStyleData.ArchitectureStyleFind.rows.map((row, index) => (
                                                <div className="form-check ms-2" key={index}>
                                                    <input className="form-check-input" type="checkbox" value={row.id} id={`flexCheckDefault${index}`} name="architectureStyles" 
                                                    onChange={handleCheckboxChange('architectureStyles')} checked={filters.architectureStyles.includes(`${row.id}`)}/>
                                                    <label className="form-check-label ms-2 text-white" htmlFor={`flexCheckDefault${index}`}>
                                                        {row.title}
                                                    </label>
                                                </div>
                                            ))
                                        )}                                       
                                    </div>
                                </div>
                            </div>
                            <div className="btns-block mt-5">
                                <button type="button" className="btn bg-primary src-btn text-white rounded-pill mr-2" onClick={onApplyFilters}>Search</button>
                                <button type="button" className="btn text-primary cancel-btn bg-transparent rounded-pill" onClick={onClearFilters}>Clear</button>
                            </div>
                        </div> */}
                    </aside>
                </div>
                <div className="py-3 bg-primary  position-absolute filter-collapse-btn-block">
                    <button
                        className="btn filter-collapse-btn text-secondary p-1  d-flex justify-content-center align-items-center bg-primary"
                        type="button" onClick={toggleSidebar} aria-expanded="false"
                        aria-controls="collapseExample">
                        <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path fillRule="evenodd" clipRule="evenodd"
                                d="M11.3492 5.90677C11.5506 5.7345 11.8122 5.64924 12.0765 5.66975C12.3407 5.69025 12.586 5.81483 12.7585 6.01611L20.7585 15.3494C20.9138 15.5307 20.9991 15.7615 20.9991 16.0001C20.9991 16.2388 20.9138 16.4695 20.7585 16.6508L12.7585 25.9841C12.5832 26.1755 12.3403 26.2913 12.0812 26.3069C11.8221 26.3226 11.567 26.2368 11.37 26.0678C11.1729 25.8988 11.0493 25.6598 11.0253 25.4014C11.0013 25.1429 11.0787 24.8852 11.2412 24.6828L18.6825 16.0001L11.2412 7.31744C11.0686 7.11634 10.9829 6.85495 11.0029 6.5907C11.0229 6.32645 11.1469 6.08094 11.3478 5.90811"
                                fill="black" />
                        </svg>

                    </button>
                </div>
            </div>
        </>
    );
};

export default FilterSidebar;