import { useState, useEffect, useRef } from "react";
import SkillCard from "../SkillCard/SkillCard.jsx";
import "./SingleProject.css";

function SingleProject({ image, title, description, skills, id, nbImage }) {
    const [imageID, setImageID] = useState(1);
    const [isFading, setIsFading] = useState(true);
    const intervalRef = useRef(null);
    const color = ["blue", "green", "purple", "red", "yellow"]

    const handleChangeImage = (direction) => {
        if (nbImage <= 1) return;

        setIsFading(false);

        setTimeout(() => {
            setImageID((prevID) =>
                direction === 1
                    ? (prevID % nbImage) + 1
                    : prevID === 1 ? nbImage : prevID - 1
            );
            setIsFading(true);
        }, 300);

        clearInterval(intervalRef.current);
        startAutoSlide();
    };

    const startAutoSlide = () => {
        intervalRef.current = setInterval(() => {
            handleChangeImage(1);
        }, 5000);
    };

    useEffect(() => {
        startAutoSlide();
        return () => clearInterval(intervalRef.current);
    }, []);

    return (
        <div className="single-project">
            <div className="single-project-left">
                <button onClick={() => handleChangeImage(-1)} className="arrow preview">{'<'}</button>

                <img
                    src={`/assets/images/${image}/${image}_${imageID}.png`}
                    alt={image}
                    className={isFading ? 'fade-in' : 'fade-out'}
                />

                <button onClick={() => handleChangeImage(1)} className="arrow next">{'>'}</button>
            </div>

            <div className="single-project-right">
                <div className="single-project-right-top">
                    <div className={`single-project-line color-${color[(id-1)%color.length]}`}></div>
                    <h3 className="single-project-title">{title}</h3>
                </div>

                <div className="single-project-right-bottom">
                    <p className="single-project-description" style={{ whiteSpace: "pre-line" }}>
                        {description}
                    </p>

                    <ul className="single-project-skills-list">
                        {skills.map((skill) => (
                            <li key={skill}>
                                <SkillCard text={skill} />
                            </li>
                        ))}
                    </ul>

                    <p className="single-project-link">Learn more</p>
                </div>
            </div>
        </div>
    );
}

export default SingleProject;
