import SingleProject from "../SingleProject/SingleProject.jsx";
import "./Projects.css"
import React, {useEffect, useState} from "react";
import {Link, useLocation} from "react-router-dom";
import NavBar from "../NavBar/NavBar.jsx";
import Filter from "../../pages/Projects/components/Filter/Filter.jsx";

function Projects() {
    const [projects, setProjects] = useState([]);
    const [error, setError] = useState(null);
    const location = useLocation();

    const [filters, setFilters] = useState({
        category: [],
        technology: [],
        yearOrder: "asc",
    });


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


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

    if (location.pathname === '/') {
        return (
            <section id="projects-section">
                <h1 className="section-title">Projects</h1>
                <div className="projects-section-list">
                    {projects
                        .filter(project => project.id <= 3)
                        .map(project => (
                            <SingleProject
                                image={project.image_name}
                                title={project.title}
                                description={project.short_description}
                                skills={project.skills}
                                id={project.id}
                                school={project.school}
                                beginningYear={project.beginning_year}
                                endYear={project.end_year}
                            />
                        ))}
                </div>
                <div className="show-more-container">
                    <Link to="/projects" className="projects-link">Show more</Link>
                </div>
            </section>
        )
    }else if (location.pathname === '/projects') {
        return (
            <section id="projects-section">
                <div className="projects-section-header">
                    <NavBar />
                    <h1 className="section-title">All Projects</h1>
                    <p className="projects-section-subtitle">Here you can find a collection of my work.</p>
                    <Filter filters={filters} setFilters={setFilters} />
                </div>
                <div className="projects-section-list">
                    {projects
                        .filter(project => {
                            const categoryFilters = filters.category;

                            if (categoryFilters.length > 0) {
                                const isSchool = project.school === 1;
                                const isFilterSchool = categoryFilters.includes("school");
                                const isFilterPersonal = categoryFilters.includes("personal");

                                if ((isSchool && !isFilterSchool) || (!isSchool && !isFilterPersonal)) {
                                    return false;
                                }
                            }

                            if (filters.technology.length > 0) {
                                const isSkill = filters.technology.every(tech => project.skills.includes(tech));
                                if(!isSkill){
                                    return false
                                }
                            }
                            return true;
                        })
                        .sort((a, b) => {
                            const aInProgress = !a.end_year;
                            const bInProgress = !b.end_year;

                            if (filters.yearOrder === "asc") {
                                const yearDiff = a.beginning_year - b.beginning_year;
                                if (yearDiff !== 0) return yearDiff;

                                if (!aInProgress && bInProgress) return -1;
                                if (aInProgress && !bInProgress) return 1;
                                return 0;
                            } else if (filters.yearOrder === "desc") {
                                const yearDiff = b.beginning_year - a.beginning_year;
                                if (yearDiff !== 0) return yearDiff;

                                if (aInProgress && !bInProgress) return -1;
                                if (!aInProgress && bInProgress) return 1;
                                return 0;
                            } else {
                                return 0;
                            }
                        })
                        .map(project => (
                        <SingleProject
                            image={project.image_name}
                            title={project.title}
                            description={project.short_description}
                            skills={project.skills}
                            id={project.id}
                            nbImage={project.nb_image}
                            school={project.school}
                            beginningYear={project.beginning_year}
                            endYear={project.end_year}
                        />
                    ))}
                </div>
                <div className="projects-back-link">
                    <Link to="/" className="projects-link">← Back to Home</Link>
                </div>
            </section>
        )
    }
}


export default Projects