import React, { useState, useRef, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import Breadcrumbs from "../../../../commonComponents/breadcrumbs/Breadcrumbs";
import { Info, UploadCloud, X } from "lucide-react";
import ReactQuill from "react-quill-new";
import "react-quill-new/dist/quill.snow.css";
import { toast } from "sonner";
import axios from "axios";

const NewCategory = () => {
  const navigate = useNavigate();
  const location = useLocation();

  const API_URL = import.meta.env.VITE_API_URL;

  // 🟧 if editing, this contains the category object
  const categoryFromState = location.state?.category || null;

  const [title, setTitle] = useState("");
  const [file, setFile] = useState(null); // {file, preview} for new upload
  const [description, setDescription] = useState("");
  const [existingImage, setExistingImage] = useState(""); // 🟧 for edit mode
  const [loading, setLoading] = useState(false);

  const fileInputRef = useRef(null);

  /* --------------------- LOAD EDIT MODE DATA --------------------- */
  useEffect(() => {
    if (categoryFromState) {
      console.log("EDIT MODE CATEGORY:", categoryFromState);

      setTitle(categoryFromState.name || "");
      setDescription(categoryFromState.description || "");

      // existing image from DB
      if (categoryFromState.image) {
        setExistingImage(`${API_URL}${categoryFromState.image}`);
      }
    }
  }, [categoryFromState]);

  /* --------------------- QUILL CONFIG ---------------------------- */
  const modules = {
    toolbar: [
      ["bold", "italic", "underline"],
      [{ list: "ordered" }, { list: "bullet" }],
      ["link"],
    ],
  };

  /* --------------------- UPLOAD IMAGE ---------------------------- */
  const handleUpload = (e) => {
    const selected = e.target.files[0];
    if (!selected) return;

    if (!selected.type.startsWith("image/")) {
      toast.error("Only images allowed.");
      return;
    }

    setFile({
      file: selected,
      preview: URL.createObjectURL(selected),
    });

    // remove old existing image preview
    setExistingImage("");
  };

  /* --------------------- SAVE CATEGORY ---------------------------- */
  const handleSave = async () => {
    try {
      if (!title.trim()) return toast.error("Category name is required");

      // IMAGE REQUIRED ONLY IN CREATE MODE
      if (!file && !existingImage) {
        return toast.error("Upload an image");
      }

      setLoading(true);

      const formData = new FormData();
      formData.append("name", title);
      formData.append("description", description);

      // If new image uploaded
      if (file) {
        formData.append("image", file.file);
      }

      /* --------------------- EDIT MODE --------------------- */
      if (categoryFromState?._id) {
        await axios.put(
          `${API_URL}/api/category/updateCategory/${categoryFromState._id}`,
          formData
        );

        toast.success("Category updated successfully!");
      }
      /* --------------------- CREATE MODE --------------------- */
      else {
        await axios.post(`${API_URL}/api/category/createCategory`, formData);
        toast.success("Category created successfully!");
      }

      navigate("/admin/category");
    } catch (err) {
      toast.error(err.response?.data?.message || "Error saving category");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">

      <Breadcrumbs
        paths={[
          { label: "Category", to: "/admin/category" },
          { label: categoryFromState ? "Edit Category" : "New Category" },
        ]}
      />

      {/* HEADER */}
      <div className="sticky top-12 bg-white shadow-sm">
        <div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
          <h1 className="text-2xl font-semibold">
            {categoryFromState ? "Edit Category" : "New Category"}
          </h1>

          <div className="flex gap-3">
            <button
              onClick={() => navigate("/admin/category")}
              className="px-4 py-2 rounded-lg border hover:bg-orange-50 text-gray-700"
            >
              Cancel
            </button>

            <button
              onClick={handleSave}
              className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-500"
            >
              {loading ? "Saving..." : "Save"}
            </button>
          </div>
        </div>
      </div>

      {/* CONTENT */}
      <div className="max-w-6xl mx-auto p-6 space-y-6">

        {/* BASIC INFO */}
        <section className="bg-white rounded-xl p-6 shadow-sm">
          <h2 className="text-xl font-semibold flex items-center gap-2">
            Basic Info
            <Info className="w-5 h-5 text-orange-500" />
          </h2>

          {/* Name */}
          <div className="mt-4">
            <label className="text-sm">Category Name *</label>
            <input
              className="w-full border rounded-lg px-4 py-3 mt-1"
              placeholder="Enter category name"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </div>

          {/* IMAGE */}
          <div className="mt-6">
            <label className="font-medium text-sm">Image *</label>

            {/* SHOW EXISTING IMAGE (EDIT MODE) */}
            {existingImage && !file && (
              <div className="relative w-48 h-48 mt-3 border rounded-lg overflow-hidden">
                <img
                  src={existingImage}
                  className="w-full h-full object-cover"
                />

                <button
                  onClick={() => setExistingImage("")}
                  className="absolute top-2 right-2 bg-white rounded-full p-1 shadow"
                >
                  <X size={16} />
                </button>
              </div>
            )}

            {/* NEW UPLOADED IMAGE */}
            {file && (
              <div className="relative w-48 h-48 mt-3 border rounded-lg overflow-hidden">
                <img
                  src={file.preview}
                  className="w-full h-full object-cover"
                />

                <button
                  onClick={() => setFile(null)}
                  className="absolute top-2 right-2 bg-white rounded-full p-1 shadow"
                >
                  <X size={16} />
                </button>
              </div>
            )}

            {/* UPLOAD BUTTON (when no image selected) */}
            {!existingImage && !file && (
              <div
                onClick={() => fileInputRef.current.click()}
                className="border-2 border-dashed rounded-lg h-44 flex justify-center items-center cursor-pointer mt-2 hover:border-orange-600 hover:bg-orange-50"
              >
                <UploadCloud className="text-orange-600" size={36} />
                <p className="text-gray-600 ml-2">Upload Image</p>
              </div>
            )}

            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleUpload}
            />
          </div>
        </section>

        {/* DESCRIPTION */}
        <section className="bg-white rounded-xl p-6 shadow-sm">
          <h2 className="text-xl font-semibold mb-4">Description</h2>

          <ReactQuill
            theme="snow"
            modules={modules}
            value={description}
            onChange={setDescription}
            placeholder="Write description..."
            className="min-h-[150px]"
          />
        </section>

      </div>
    </div>
  );
};

export default NewCategory;
