import { useEffect, useState } from "react";

const Genres = ({ id }) => {
  const [genres, setGenres] = useState([]);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    if (!id) return; // Prevent API call if id is undefined or null

    const fetchGenres = async () => {
      setLoading(true);
      setNotFound(false); // Reset the notFound state on each new request
      try {
        const response = await fetch(
          `https://api.themoviedb.org/3/movie/${id}?api_key=8216fbb9997cd81a67471e6cb5a6f2df`
        );

	if (response.status === 404) {
	  console.log('test');
          setNotFound(true);
          return;
        }
        if (!response.ok) {
          // If the response is not okay, just set the notFound flag
          setNotFound(true);
          return;
        }

        const data = await response.json();
        setGenres(data.genres || []);
      } catch (err) {
        console.error("An error occurred while fetching genres:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchGenres();
  }, [id]);

  if (loading) {
    return <div className="text-white/60 text-xs">Loading genres...</div>;
  }

  if (notFound) {
    // Instead of throwing an error, simply render nothing if the movie is not found
    return null;
  }

  return (
    <div className="text-white/60 gap-x-3 text-xs flex flex-row flex-wrap relative">
      {genres.map((genre, index) => (
        <div key={index}>{genre.name}</div>
      ))}
    </div>
  );
};

export default Genres;
