import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { uploadImage, createPost } 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 CreatePost() {
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [file, setFile] = useState(null);
  const navigate = useNavigate();

  // ✅ Vérification de l'authentification : Redirection vers /login si l'utilisateur n'est pas connecté
  useEffect(() => {
    if (!getToken()) {
      navigate("/admin/login");
    }
  }, [navigate]);

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      console.log("📢 Tentative d'upload de l'image...");
      const imageId = await uploadImage(file);

      console.log("📢 Création du post avec l'image mise en avant...");
      await createPost(title, content, imageId);

      alert("✅ Post créé avec succès !");
      navigate("/admin/gestion-articles"); // Redirection après la création
    } catch (error) {
      alert("❌ Erreur lors de la création du post.");
    }
  };

  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 }}>
          {/* ✅ Bouton Retour à la Gestion des Articles */}
          <Button
            startIcon={<ArrowBack />}
            variant="outlined"
            color="secondary"
            onClick={() => navigate("/admin/gestion-articles")}
            sx={{ mb: 2 }}
          >
            Retour à la gestion des articles
          </Button>

          {/* ✅ Titre de la page */}
          <Typography variant="h4" sx={{ fontWeight: "bold", textAlign: "center", mb: 3 }}>
            Créer un article
          </Typography>

          {/* ✅ Formulaire */}
          <form onSubmit={handleSubmit}>
            <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 }}>
                Image en vedette :
              </Typography>
              <Input
                type="file"
                accept="image/*"
                onChange={(e) => setFile(e.target.files[0])}
                required
                sx={{ display: "block", mb: 2 }}
              />
            </Box>

            {/* ✅ Bouton Publier */}
            <Button
              type="submit"
              variant="contained"
              color="primary"
              fullWidth
              startIcon={<Publish />}
              sx={{ mt: 3 }}
            >
              Publier l'article
            </Button>
          </form>
        </Paper>
      </Container>
    </Box>
  );
}

export default CreatePost;