import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { getPostById, updatePost, uploadImage } from "../wordpress";
import { getToken } from "../auth";
import {
  Box, Container, Typography, TextField, Button, Paper, Input, IconButton
} from "@mui/material";
import { ArrowBack, Publish } from "@mui/icons-material";

function EditPost() {
  const { id } = useParams(); // ✅ Récupère l'ID de l'article depuis l'URL
  const navigate = useNavigate();
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [file, setFile] = useState(null);
  const [loading, setLoading] = useState(true);

  // ✅ Vérification de l'authentification
  useEffect(() => {
    if (!getToken()) {
      navigate("/admin/login");
    }
  }, [navigate]);

  // ✅ Récupérer les données de l'article
  useEffect(() => {
    const fetchPost = async () => {
      try {
        const post = await getPostById(id);
        setTitle(post.title.rendered);
        setContent(post.content.rendered.replace(/(<([^>]+)>)/gi, "")); // Enlever le HTML
        setLoading(false);
      } catch (error) {
        console.error("Erreur chargement article :", error);
        navigate("/admin/gestion-articles"); // Redirige si erreur
      }
    };

    fetchPost();
  }, [id, navigate]);

  const handleUpdate = async (e) => {
    e.preventDefault();
    try {
      const updatedPost = await updatePost(id, title, content, file);
      alert("✅ Article mis à jour avec succès !");
      navigate("/admin/gestion-articles"); // Redirige après modification
    } catch (error) {
      alert("❌ Erreur lors de la mise à jour de l'article.");
    }
  };

  if (loading) return <Typography>Chargement...</Typography>;

  return (
    <Box
      sx={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        backgroundImage: "url('https://source.unsplash.com/1600x900/?office,writing')",
        backgroundSize: "cover",
        backgroundPosition: "center",
      }}
    >
      <Container maxWidth="sm">
        <Paper elevation={6} sx={{ padding: 4, borderRadius: 3 }}>
          <Button
            startIcon={<ArrowBack />}
            variant="outlined"
            color="secondary"
            onClick={() => navigate("/admin/gestion-articles")}
            sx={{ mb: 2 }}
          >
            Retour à la gestion des articles
          </Button>

          <Typography variant="h4" sx={{ fontWeight: "bold", textAlign: "center", mb: 3 }}>
            Modifier l'article
          </Typography>

          <form onSubmit={handleUpdate}>
            <TextField
              label="Titre de l'article"
              fullWidth
              margin="normal"
              variant="outlined"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              required
            />

            <TextField
              label="Contenu"
              fullWidth
              margin="normal"
              variant="outlined"
              multiline
              rows={4}
              value={content}
              onChange={(e) => setContent(e.target.value)}
              required
            />

            {/* Upload de l'image */}
            <Box sx={{ mt: 2 }}>
              <Typography variant="body1" sx={{ fontWeight: "bold", mb: 1 }}>
                Nouvelle image (facultatif) :
              </Typography>
              <Input
                type="file"
                accept="image/*"
                onChange={(e) => setFile(e.target.files[0])}
                sx={{ display: "block", mb: 2 }}
              />
            </Box>

            <Button
              type="submit"
              variant="contained"
              color="primary"
              fullWidth
              startIcon={<Publish />}
              sx={{ mt: 3 }}
            >
              Mettre à jour
            </Button>
          </form>
        </Paper>
      </Container>
    </Box>
  );
}

export default EditPost;