import './Filter.css';
import React, {useEffect, useState} from "react";

function Filter({ filters, setFilters }) {
    const [isFilterVisible, setIsFilterVisible] = useState(false);
    const showFilters = () => setIsFilterVisible(true);
    const hideFilters = () => setIsFilterVisible(false);
    const [skills, setSkills] = useState([]);
    const [error, setError] = useState(null);


    const handleCategoryFilter = (category) => {
        setFilters(prev => {
            const alreadySelected = prev.category.includes(category);
            return {
                ...prev,
                category: alreadySelected
                    ? prev.category.filter(c => c !== category)
                    : [...prev.category, category],
            };
        });
    };

    const toggleTechnologyFilter = (tech) => {
        setFilters(prev => {
            const alreadySelected = prev.technology.includes(tech);
            return {
                ...prev,
                technology: alreadySelected
                    ? prev.technology.filter(t => t !== tech)
                    : [...prev.technology, tech],
            };
        });
    };

    const setYearOrder = (order) => {
        setFilters(prev => ({
            ...prev,
            yearOrder: prev.yearOrder === order ? null : order
        }));
    };

    const resetFilters = () => {
        setFilters({
            category: [],
            technology: [],
            yearOrder: filters.yearOrder,
        });
    };



    useEffect(() => {
        if (isFilterVisible) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = '';
        }

        return () => {
            document.body.style.overflow = '';
        };
    }, [isFilterVisible]);




    useEffect(() => {
        const fetchSkills = async () => {
            try {
                const response = await fetch('/api/skills/');
                if (!response.ok) {
                    throw new Error(`Erreur HTTP: ${response.status}`);
                }
                const data = await response.json();
                setSkills(data.data);
            } catch (err) {
                setError(err.message);
            }
        };
        fetchSkills();
    }, []);

    if (error) {
        return <div>Error retrieving data: {error}</div>;
    }



    return (
        <div>
            <button className="filter-btn" onClick={showFilters}>
                <svg xmlns="http://www.w3.org/2000/svg" height="30" viewBox="0 -960 960 960" width="30" fill="currentColor">
                    <path d="M440-160q-17 0-28.5-11.5T400-200v-240L168-736q-15-20-4.5-42t36.5-22h560q26 0 36.5 22t-4.5 42L560-440v240q0 17-11.5 28.5T520-160h-80Zm40-308 198-252H282l198 252Zm0 0Z"/>
                </svg>
            </button>

            {isFilterVisible ? <div className="filter-overlay" onClick={hideFilters}></div> : null}

            <div className={`filter-sidebar ${isFilterVisible ? 'visible' : ''}`}>
                <div className="filter-sidebar-header">
                    <h3>Filter Projects</h3>
                    <button className="close-filter-btn" onClick={hideFilters}>
                        <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="currentColor">
                            <path d="m256-200-56-56 224-224-224-224 56-56 224 224 224-224 56 56-224 224 224 224-56 56-224-224-224 224Z"/>
                        </svg>
                    </button>
                </div>
                <div className="filter-sidebar-content">
                    <div className="filter-group">
                        <button
                            className={`filter-tag ${filters.category.length === 0 && filters.technology.length === 0 ? "active" : ""}`}
                            onClick={resetFilters}
                        >All</button>

                    </div>
                    <h4>Category</h4>
                    <div className="filter-group">
                        <button
                            className={`filter-tag ${filters.category.includes("school") ? "active" : ""}`}
                            onClick={() => handleCategoryFilter("school")}
                        >School</button>
                        <button
                            className={`filter-tag ${filters.category.includes("personal") ? "active" : ""}`}
                            onClick={() => handleCategoryFilter("personal")}
                        >Personal</button>
                    </div>
                    <h4>Technology</h4>
                    <div className="filter-group">
                        {skills.map(skill => (
                            <button
                                className={`filter-tag ${filters.technology.includes(skill.name) ? "active" : ""}`}
                                onClick={() => toggleTechnologyFilter(skill.name)}
                            >{skill.name}</button>
                        ))}
                    </div>
                    <h4>YEAR</h4>
                    <div className="filter-group">
                        <button
                            className={`filter-tag ${filters.yearOrder === "asc" ? "active" : ""}`}
                            onClick={() => setYearOrder("asc")}
                        >Ascending</button>
                        <button
                            className={`filter-tag ${filters.yearOrder === "desc" ? "active" : ""}`}
                            onClick={() => setYearOrder("desc")}
                        >Descending</button>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Filter;