import { useEffect, useState } from "react";
import { fetchPosts, deletePost } from "../../wordpress";
import { Box, Typography, Button, CircularProgress, Paper, Grid } from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

function PostList() {
    const [posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        async function loadPosts() {
            try {
                const data = await fetchPosts();
                setPosts(data);
            } catch (err) {
                setError("⚠️ Impossible de récupérer les articles.");
                console.error("Erreur lors de la récupération des articles :", err);
            } finally {
                setLoading(false);
            }
        }
        loadPosts();
    }, []);

    const handleDelete = async (postId) => {
        if (window.confirm("❌ Es-tu sûr de vouloir supprimer cet article ?")) {
            try {
                await deletePost(postId);
                setPosts(posts.filter((post) => post.id !== postId));
                toast.success("✅ Article supprimé avec succès !");
            } catch (err) {
                console.error("Erreur suppression :", err);
                toast.error("⚠️ Erreur lors de la suppression.");
            }
        }
    };

    return (
        <Box sx={{ maxWidth: "900px", margin: "auto", mt: 5 }}>
            <Typography variant="h4" sx={{ fontWeight: "bold", textAlign: "center", mb: 3 }}>
                📋 Liste des Articles
            </Typography>

            {loading && (
                <Box sx={{ textAlign: "center", mt: 4 }}>
                    <CircularProgress />
                </Box>
            )}

            {error && (
                <Typography color="error" textAlign="center" sx={{ mb: 3 }}>
                    {error}
                </Typography>
            )}

            {!loading && posts.length === 0 && (
                <Typography textAlign="center" sx={{ mt: 3 }}>
                    Aucun article trouvé.
                </Typography>
            )}

            <Grid container spacing={3}>
                {posts.map((post) => (
                    <Grid item xs={12} sm={6} md={4} key={post.id}>
                        <Paper sx={{ padding: 3, boxShadow: 3, textAlign: "center" }}>
                            <Typography variant="h6" sx={{ fontWeight: "bold", mb: 2 }}>
                                {post.title.rendered}
                            </Typography>
                            <Button
                                variant="contained"
                                color="error"
                                startIcon={<DeleteIcon />}
                                onClick={() => handleDelete(post.id)}
                                sx={{ fontWeight: "bold" }}
                            >
                                Supprimer
                            </Button>
                        </Paper>
                    </Grid>
                ))}
            </Grid>
        </Box>
    );
}

export default PostList;