import React, { useState, useEffect } from "react";
import axios from "axios";
import { toast } from "react-toastify";
import { FiX, FiEdit2, FiTrash2 } from "react-icons/fi";

const GalleryAdmin = () => {
  const [galleryItems, setGalleryItems] = useState([]);
  const [category, setCategory] = useState("Awards & Achievements");
  const [caption, setCaption] = useState("");
  const [date, setDate] = useState("");
  const [media, setMedia] = useState(null);
  const [mediaPreview, setMediaPreview] = useState(null);
  const [mediaType, setMediaType] = useState("image");
  const [editMode, setEditMode] = useState(false);
  const [editItemId, setEditItemId] = useState(null);

  const categories = [
    { label: "Awards & Achievements", value: "Awards & Achievements" },
    { label: "Client Testimonials", value: "Client Testimonials" },
  ];

  // Fetch all gallery items
  const fetchGalleryItems = async () => {
    try {
      const res = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/api/gallery`);
      setGalleryItems(res.data);
    } catch (err) {
      console.error("Error fetching gallery items", err);
      toast.error("Failed to load gallery items");
    }
  };

  useEffect(() => {
    fetchGalleryItems();
  }, []);

  // Reset the form
  const resetForm = () => {
    setCategory("Awards & Achievements");
    setCaption("");
    setDate("");
    setMedia(null);
    setMediaPreview(null);
    setMediaType("image");
    setEditMode(false);
    setEditItemId(null);
  };

  // Handle media selection
  const handleMediaChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;

    setMedia(file);
    
    // Check if file is video
    if (file.type.includes("video")) {
      setMediaType("video");
      setMediaPreview(URL.createObjectURL(file));
    } else {
      setMediaType("image");
      setMediaPreview(URL.createObjectURL(file));
    }
  };

  // Handle form submit (add or update)
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!category || (!editMode && !media)) {
      toast.error("Category and media file are required!");
      return;
    }

    const formData = new FormData();
    formData.append("category", category);
    formData.append("caption", caption);
    formData.append("date", date);
    formData.append("type", mediaType);
    if (media) formData.append("media", media);

    try {
      if (editMode) {
        await axios.put(
          `${process.env.REACT_APP_API_BASE_URL}/api/gallery/${editItemId}`,
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          }
        );
        toast.success("Gallery item updated successfully!");
      } else {
        await axios.post(
          `${process.env.REACT_APP_API_BASE_URL}/api/gallery`,
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          }
        );
        toast.success("Gallery item added successfully!");
      }

      resetForm();
      fetchGalleryItems();
    } catch (err) {
      console.error("Failed to save gallery item", err);
      toast.error("Error saving gallery item");
    }
  };

  // Load item into form for editing
  const handleEdit = (item) => {
    setCategory(item.category);
    setCaption(item.caption);
    setDate(item.date || "");
    setMedia(null);
    setMediaType(item.type);
    setMediaPreview(`${process.env.REACT_APP_API_BASE_URL}${item.url}`);
    setEditMode(true);
    setEditItemId(item.id);
  };

  // Delete an item
  const handleDelete = async (id) => {
    if (!window.confirm("Are you sure you want to delete this item?")) return;

    try {
      await axios.delete(`${process.env.REACT_APP_API_BASE_URL}/api/gallery/${id}`);
      toast.success("Item deleted");
      fetchGalleryItems();
    } catch (err) {
      console.error("Failed to delete", err);
      toast.error("Failed to delete item");
    }
  };

  return (
    <div className="p-6 min-h-screen bg-gray-50">
      <h1 className="text-3xl font-bold text-blue-900 mb-6">
        {editMode ? "Edit Gallery Item" : "Add New Gallery Item"}
      </h1>

      {/* FORM */}
      <form onSubmit={handleSubmit} className="space-y-4 max-w-md mx-auto bg-white p-6 rounded-lg shadow">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Category</label>
          <select
            value={category}
            onChange={(e) => setCategory(e.target.value)}
            className="w-full border p-2 rounded"
            required
          >
            {categories.map((cat) => (
              <option key={cat.value} value={cat.value}>
                {cat.label}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Media Type</label>
          <select
            value={mediaType}
            onChange={(e) => setMediaType(e.target.value)}
            className="w-full border p-2 rounded"
            disabled={editMode && !media} // Disable if editing and no new media selected
          >
            <option value="image">Image</option>
            <option value="video">Video</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {mediaType === "image" ? "Image" : "Video"} Upload
          </label>
          <input
            type="file"
            accept={mediaType === "image" ? "image/*" : "video/*"}
            onChange={handleMediaChange}
            className="w-full"
            required={!editMode}
          />
        </div>

        {mediaPreview && (
          <div className="relative">
            {mediaType === "image" ? (
              <img
                src={mediaPreview}
                alt="Preview"
                className="h-48 w-full object-contain rounded border"
              />
            ) : (
              <video
                controls
                className="h-48 w-full object-contain rounded border"
              >
                <source src={mediaPreview} type="video/mp4" />
              </video>
            )}
            <button
              type="button"
              onClick={() => {
                setMedia(null);
                setMediaPreview(null);
              }}
              className="absolute top-2 right-2 bg-black bg-opacity-50 text-white p-1 rounded-full"
            >
              <FiX size={18} />
            </button>
          </div>
        )}

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Caption</label>
          <input
            type="text"
            value={caption}
            onChange={(e) => setCaption(e.target.value)}
            className="w-full border p-2 rounded"
            placeholder="Enter caption"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Date (optional)</label>
          <input
            type="date"
            value={date}
            onChange={(e) => setDate(e.target.value)}
            className="w-full border p-2 rounded"
          />
        </div>

        <div className="flex justify-between gap-4">
          <button
            type="submit"
            className="flex-1 bg-blue-900 text-white py-2 rounded hover:bg-blue-800"
          >
            {editMode ? "Update Item" : "Save Item"}
          </button>
          {editMode && (
            <button
              type="button"
              onClick={resetForm}
              className="flex-1 bg-gray-300 text-black py-2 rounded hover:bg-gray-400"
            >
              Cancel
            </button>
          )}
        </div>
      </form>

      {/* GALLERY ITEMS LIST */}
      <div className="mt-10">
        <h2 className="text-2xl font-semibold text-blue-800 mb-4">All Gallery Items</h2>
        <div className="grid md:grid-cols-3 sm:grid-cols-2 gap-6">
          {galleryItems.map((item) => (
            <div
              key={item.id}
              className="bg-white p-4 rounded-xl shadow hover:shadow-lg transition-all relative"
            >
              {item.type === "image" ? (
                <img
                  src={`${process.env.REACT_APP_API_BASE_URL}${item.url}`}
                  alt={item.caption || "Gallery item"}
                  className="h-56 w-full object-cover rounded mb-3"
                />
              ) : (
                <video
                  className="h-56 w-full object-cover rounded mb-3"
                  controls
                >
                  <source src={`${process.env.REACT_APP_API_BASE_URL}${item.url}`} type="video/mp4" />
                </video>
              )}
              
              <p className="text-sm font-medium text-gray-700 mb-1">
                <span className="font-semibold">Category:</span> {item.category}
              </p>
              {item.caption && (
                <p className="text-sm text-gray-600 mb-1 line-clamp-2">
                  <span className="font-semibold">Caption:</span> {item.caption}
                </p>
              )}
              {item.date && (
                <p className="text-xs text-gray-500">
                  {new Date(item.date).toLocaleDateString()}
                </p>
              )}

              <div className="flex justify-between mt-3">
                <button
                  onClick={() => handleEdit(item)}
                  className="flex items-center text-blue-600 hover:text-blue-800"
                >
                  <FiEdit2 className="mr-1" /> Edit
                </button>
                <button
                  onClick={() => handleDelete(item.id)}
                  className="flex items-center text-red-600 hover:text-red-800"
                >
                  <FiTrash2 className="mr-1" /> Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default GalleryAdmin;