import { useState, useEffect } from "react";
import { Box, Typography, Button, CircularProgress } from "@mui/material";
import { useParams, useNavigate } from "react-router-dom";
import api from "../api";

const PostDetails = () => {
  const { slug } = useParams();
  const [post, setPost] = useState(null);
  const [image, setImage] = useState(null);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchPost = async () => {
      if (!slug) {
        console.error("❌ Erreur : aucun slug fourni !");
        return;
      }

      try {
        console.log(`📢 Requête API pour le slug : ${slug}`);
        const response = await api.get(`wp/v2/posts?slug=${slug}&_fields=id,title,content,featured_media,date`);

        if (response.data.length > 0) {
          const article = response.data[0];
          setPost(article);

          if (article.featured_media) {
            console.log(`📢 Récupération de l'image ID : ${article.featured_media}`);
            const mediaResponse = await api.get(`wp/v2/media/${article.featured_media}`);
            setImage(mediaResponse.data.source_url);
          }
        } else {
          console.error("❌ Aucun article trouvé avec ce slug !");
        }
      } catch (error) {
        console.error("❌ Erreur lors de la récupération de l'article :", error);
      }
    };

    fetchPost();
  }, [slug]);

  if (!post) {
    return <CircularProgress sx={{ display: "block", margin: "auto", mt: 5 }} />;
  }

  return (
    <Box sx={{ padding: "40px 20px", display: "flex", flexDirection: "column" }}>
      <Button onClick={() => navigate(-1)} variant="contained" sx={{ mt: 5, mb: 3, maxWidth: "200px" }}>
        ⬅ Retour
      </Button>

      <Typography
        variant="h1"
        sx={{
          fontWeight: "bold",
          textAlign: "center",
          mb: 4,
          fontSize: { xs: "3rem", md: "3rem", lg: "3rem" },
        }}
      >
        {post.title.rendered}
      </Typography>

      <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "40px 20px", margin: "auto" }}>
        {image && (
          <Box
            component="img"
            src={image}
            alt={post.title.rendered}
            sx={{ width: "100%", maxHeight: "400px", objectFit: "cover", borderRadius: "10px 0 10px 10px", mb: 3 }}
          />
        )}

        <Box
          sx={{
            maxWidth: "800px",
            mx: "auto",
            "& h2": { color: "#315397", mt: 4, mb: 2 },
            "& h3": { color: "#315397", mt: 3, mb: 1 },
            "& h4": { color: "#315397", mt: 2, mb: 1 },
            "& p": { mb: 2 },
          }}
          dangerouslySetInnerHTML={{ __html: post.content.rendered }}
        />
      </Box>
    </Box>
  );
};

export default PostDetails;