// import React, { useState } from "react";
// import { FiTag, FiAlignLeft, FiLayers, FiImage, FiType } from "react-icons/fi";
// import {
//   useAddCategoryMutation,
//   useGetCategoryTreeQuery,
// } from "../../features/categories/categoryAPI";

// const AddCategoryPage = () => {
//   const [form, setForm] = useState({
//     name: "",
//     description: "",
//     image: "",
//     parentId: "",
//     metaTitle: "",
//     metaDescription: "",
//   });

//   const { data, isLoading: loadingCategories } = useGetCategoryTreeQuery();
//   const [addCategory, { isLoading: adding }] = useAddCategoryMutation();
//   const categories = data?.data || [];

//   const handleChange = (e) =>
//     setForm({ ...form, [e.target.name]: e.target.value });

//   const handleSubmit = async (e) => {
//     e.preventDefault();
//     try {
//       const result = await addCategory({
//         ...form,
//         parentId: form.parentId || null,
//       }).unwrap();
//       console.log("Category added:", result);
//       alert("Category added successfully!");
//       // setForm({ name: "", description: "", parentId: "" });
//       setForm({
//         name: "",
//         description: "",
//         image: "",
//         parentId: "",
//         metaTitle: "",
//         metaDescription: "",
//       });
//     } catch (err) {
//       console.error("RTK Query error:", err);
//       const errorMsg =
//         err?.data?.message || // if server returned { message: "..." }
//         err?.error || // if network/fetch error
//         JSON.stringify(err) ||
//         "Unknown error";
//       alert("Error adding category: " + errorMsg);
//     }
//   };

//   // Flatten categories tree for dropdown
//   const flattenCategories = (nodes, level = 0) => {
//     let list = [];
//     nodes.forEach((node) => {
//       list.push({ ...node, level });
//       if (node.children?.length) {
//         list = list.concat(flattenCategories(node.children, level + 1));
//       }
//     });
//     return list;
//   };

//   const flatCategories = flattenCategories(categories);

//   return (
//     <div className="p-6 md:p-12 min-h-screen flex justify-center items-start">
//       <div className="w-full max-w-2xl bg-white rounded-2xl shadow-2xl p-10 relative">
//         <h2 className="text-3xl font-bold text-center text-blue-600 mb-8">
//           <FiLayers className="inline mr-2" /> Add New Category
//         </h2>

//         <form onSubmit={handleSubmit} className="space-y-6">
//           <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
//             {/* Category Name */}
//             <div className="flex items-center gap-3 border rounded-xl p-3 focus-within:ring-2 focus-within:ring-blue-400 transition">
//               <FiTag className="text-gray-400 text-xl" />
//               <input
//                 type="text"
//                 name="name"
//                 value={form.name}
//                 onChange={handleChange}
//                 placeholder="Category Name"
//                 required
//                 className="w-full outline-none text-gray-700 font-medium"
//               />
//             </div>

//             {/* Image URL */}
//             <div className="flex items-center gap-3 border rounded-xl p-3 focus-within:ring-2 focus-within:ring-blue-400 transition">
//               <FiImage className="text-gray-400 text-xl" />
//               <input
//                 type="text"
//                 name="image"
//                 value={form.image}
//                 onChange={handleChange}
//                 placeholder="Image URL"
//                 className="w-full outline-none text-gray-700 font-medium"
//               />
//             </div>

//             {/* Meta Title */}
//             <div className="flex items-center gap-3 border rounded-xl p-3 focus-within:ring-2 focus-within:ring-blue-400 transition">
//               <FiType className="text-gray-400 text-xl" />
//               <input
//                 type="text"
//                 name="metaTitle"
//                 value={form.metaTitle}
//                 onChange={handleChange}
//                 placeholder="Meta Title"
//                 className="w-full outline-none text-gray-700 font-medium"
//               />
//             </div>

//             {/* Parent Category */}
//             <div className="flex flex-col gap-2 border rounded-xl p-3 focus-within:ring-2 focus-within:ring-blue-400 transition">
//               <label className="text-gray-500 font-medium flex items-center gap-2">
//                 <FiLayers /> Parent Category
//               </label>
//               <select
//                 name="parentId"
//                 value={form.parentId}
//                 onChange={handleChange}
//                 className="w-full outline-none text-gray-700 font-medium"
//               >
//                 <option value="">No Parent (Main Category)</option>
//                 {loadingCategories ? (
//                   <option disabled>Loading...</option>
//                 ) : (
//                   flatCategories.map((cat) => (
//                     <option key={cat.id} value={cat.id}>
//                       {"-".repeat(cat.level * 2)} {cat.name}
//                     </option>
//                   ))
//                 )}
//               </select>
//             </div>
//           </div>

//           {/* Description (full width) */}
//           <div className="flex flex-col gap-2 border rounded-xl p-3 focus-within:ring-2 focus-within:ring-blue-400 transition">
//             <label className="text-gray-500 font-medium flex items-center gap-2">
//               <FiAlignLeft /> Description
//             </label>
//             <textarea
//               name="description"
//               value={form.description}
//               onChange={handleChange}
//               rows={4}
//               placeholder="Category description"
//               className="w-full outline-none text-gray-700 font-medium resize-none"
//             />
//           </div>

//           {/* Meta Description (full width) */}
//           <div className="flex flex-col gap-2 border rounded-xl p-3 focus-within:ring-2 focus-within:ring-blue-400 transition">
//             <label className="text-gray-500 font-medium flex items-center gap-2">
//               <FiAlignLeft /> Meta Description
//             </label>
//             <textarea
//               name="metaDescription"
//               value={form.metaDescription}
//               onChange={handleChange}
//               rows={3}
//               placeholder="Meta Description"
//               className="w-full outline-none text-gray-700 font-medium resize-none"
//             />
//           </div>

//           <button
//             type="submit"
//             disabled={adding}
//             className="w-full bg-blue-600 text-white py-3 rounded-xl font-semibold text-lg hover:bg-blue-700 transition-all shadow-md hover:shadow-lg"
//           >
//             {adding ? "Adding..." : "Add Category"}
//           </button>
//         </form>
//       </div>
//     </div>
//   );
// };

// export default AddCategoryPage;



// import React, { useState } from "react";
// import {
//   useAddCategoryMutation,
//   useGetCategoryTreeQuery,
// } from "../../features/categories/categoryAPI";

// const AddCategoryPage = () => {
//   const [form, setForm] = useState({
//     name: "",
//     description: "",
//     image: "",
//     parentId: "",
//     metaTitle: "",
//     metaDescription: "",
//   });

//   const { data, isLoading } = useGetCategoryTreeQuery();
//   const [addCategory, { isLoading: adding }] = useAddCategoryMutation();

//   const categories = data?.data || [];

//   const handleChange = (e) =>
//     setForm({ ...form, [e.target.name]: e.target.value });

//   const handleSubmit = async (e) => {
//     e.preventDefault();
//     await addCategory({
//       ...form,
//       parentId: form.parentId || null,
//     }).unwrap();

//     setForm({
//       name: "",
//       description: "",
//       image: "",
//       parentId: "",
//       metaTitle: "",
//       metaDescription: "",
//     });
//   };

//   // Flatten category tree
//   const flattenCategories = (nodes, level = 0) =>
//     nodes.flatMap((n) => [
//       { ...n, level },
//       ...(n.children ? flattenCategories(n.children, level + 1) : []),
//     ]);

//   const flatCategories = flattenCategories(categories);

//   return (
//     <div className="min-h-screen bg-gray-50 flex justify-center py-12 px-4">
//       <div className="w-full max-w-3xl bg-white rounded-xl shadow-sm border p-8">

//         {/* Header */}
//         <h2 className="text-2xl font-semibold text-gray-800 mb-1">
//           Add Category
//         </h2>
//         <p className="text-sm text-gray-500 mb-8">
//           Create main or sub-categories for products
//         </p>

//         <form onSubmit={handleSubmit} className="space-y-6">

//           {/* Name + Parent */}
//           <div className="grid md:grid-cols-2 gap-5">
//             <Input
//               label="Category Name"
//               name="name"
//               value={form.name}
//               onChange={handleChange}
//               required
//             />

//             <Select
//               label="Parent Category"
//               name="parentId"
//               value={form.parentId}
//               onChange={handleChange}
//               options={flatCategories}
//               loading={isLoading}
//             />
//           </div>

//           {/* Image */}
//           <Input
//             label="Image URL"
//             name="image"
//             value={form.image}
//             onChange={handleChange}
//           />

//           {/* Description */}
//           <Textarea
//             label="Description"
//             name="description"
//             value={form.description}
//             onChange={handleChange}
//           />

//           {/* SEO */}
//           <div className="border rounded-lg p-5 bg-gray-50 space-y-5">
//             <p className="text-sm font-medium text-gray-700">
//               SEO Settings
//             </p>

//             <Input
//               label="Meta Title"
//               name="metaTitle"
//               value={form.metaTitle}
//               onChange={handleChange}
//             />

//             <Textarea
//               label="Meta Description"
//               name="metaDescription"
//               value={form.metaDescription}
//               onChange={handleChange}
//               rows={3}
//             />
//           </div>

//           {/* Submit */}
//           <div className="flex justify-end">
//             <button
//               type="submit"
//               disabled={adding}
//               className="px-6 py-2.5 rounded-lg bg-blue-600 text-white text-sm font-medium hover:bg-blue-700 transition disabled:opacity-60"
//             >
//               {adding ? "Saving..." : "Save Category"}
//             </button>
//           </div>
//         </form>
//       </div>
//     </div>
//   );
// };

// /* ---------- Reusable Fields ---------- */

// const Input = ({ label, ...props }) => (
//   <div>
//     <label className="block text-sm font-medium text-gray-600 mb-1">
//       {label}
//     </label>
//     <input
//       {...props}
//       className="w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
//     />
//   </div>
// );

// const Textarea = ({ label, rows = 4, ...props }) => (
//   <div>
//     <label className="block text-sm font-medium text-gray-600 mb-1">
//       {label}
//     </label>
//     <textarea
//       {...props}
//       rows={rows}
//       className="w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none resize-none"
//     />
//   </div>
// );

// const Select = ({ label, options, loading, ...props }) => (
//   <div>
//     <label className="block text-sm font-medium text-gray-600 mb-1">
//       {label}
//     </label>
//     <select
//       {...props}
//       className="w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
//     >
//       <option value="">Main Category</option>
//       {loading ? (
//         <option>Loading...</option>
//       ) : (
//         options.map((cat) => (
//           <option key={cat.id} value={cat.id}>
//             {"—".repeat(cat.level)} {cat.name}
//           </option>
//         ))
//       )}
//     </select>
//   </div>
// );

// export default AddCategoryPage;



import React, { useState } from "react";
import {
  useAddCategoryMutation,
  useGetCategoryTreeQuery,
} from "../../features/categories/categoryAPI";

const AddCategoryPage = () => {
  const [form, setForm] = useState({
    name: "",
    description: "",
    parentId: "",
    metaTitle: "",
    metaDescription: "",
  });

  const [selectedFile, setSelectedFile] = useState(null);
  const [previewImage, setPreviewImage] = useState(null);

  const { data, isLoading } = useGetCategoryTreeQuery();
  const [addCategory, { isLoading: adding }] = useAddCategoryMutation();

  const categories = data?.data || [];

  const handleChange = (e) =>
    setForm({ ...form, [e.target.name]: e.target.value });

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setSelectedFile(file);
      setPreviewImage(URL.createObjectURL(file));
    }
  };

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

    const formData = new FormData();

    formData.append("name", form.name);
    formData.append("description", form.description);
    formData.append("parentId", form.parentId || "");
    formData.append("metaTitle", form.metaTitle);
    formData.append("metaDescription", form.metaDescription);

    if (selectedFile) {
      formData.append("image", selectedFile);
    }

    await addCategory(formData).unwrap();

    // Reset
    setForm({
      name: "",
      description: "",
      parentId: "",
      metaTitle: "",
      metaDescription: "",
    });
    setSelectedFile(null);
    setPreviewImage(null);
  };

  // Flatten category tree
  const flattenCategories = (nodes, level = 0) =>
    nodes.flatMap((n) => [
      { ...n, level },
      ...(n.children ? flattenCategories(n.children, level + 1) : []),
    ]);

  const flatCategories = flattenCategories(categories);

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 flex justify-center py-12 px-4">
      <div className="w-full max-w-3xl bg-white rounded-2xl shadow-xl border p-8 space-y-8">

        {/* Header */}
        <div>
          <h2 className="text-3xl font-bold text-gray-800">
            Create New Category
          </h2>
          <p className="text-sm text-gray-500 mt-1">
            Organize your products efficiently
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">

          {/* Name + Parent */}
          <div className="grid md:grid-cols-2 gap-5">
            <Input
              label="Category Name"
              name="name"
              value={form.name}
              onChange={handleChange}
              required
            />

            <Select
              label="Parent Category"
              name="parentId"
              value={form.parentId}
              onChange={handleChange}
              options={flatCategories}
              loading={isLoading}
            />
          </div>

          {/* Image Upload */}
          <div>
            <label className="block text-sm font-medium text-gray-600 mb-2">
              Category Image
            </label>

            <div className="flex items-center gap-6">

              {/* Preview Box */}
              <div className="w-40 h-40 border-2 border-dashed rounded-xl flex items-center justify-center bg-gray-50 overflow-hidden">
                {previewImage ? (
                  <img
                    src={previewImage}
                    alt="Preview"
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <span className="text-gray-400 text-sm">
                    No Image Selected
                  </span>
                )}
              </div>

              {/* Upload Button */}
              <label className="cursor-pointer">
                <div className="px-6 py-3 bg-blue-600 text-white rounded-xl shadow hover:bg-blue-700 transition font-medium">
                  Choose Image
                </div>
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleImageChange}
                  hidden
                />
              </label>
            </div>
          </div>

          {/* Description */}
          <Textarea
            label="Description"
            name="description"
            value={form.description}
            onChange={handleChange}
          />

          {/* SEO Section */}
          <div className="border rounded-xl p-6 bg-gray-50 space-y-5">
            <p className="text-sm font-semibold text-gray-700">
              SEO Settings
            </p>

            <Input
              label="Meta Title"
              name="metaTitle"
              value={form.metaTitle}
              onChange={handleChange}
            />

            <Textarea
              label="Meta Description"
              name="metaDescription"
              value={form.metaDescription}
              onChange={handleChange}
              rows={3}
            />
          </div>

          {/* Submit */}
          <div className="flex justify-end pt-4 border-t">
            <button
              type="submit"
              disabled={adding}
              className="px-8 py-3 rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-semibold shadow-lg hover:scale-105 transition-all duration-200 disabled:opacity-60"
            >
              {adding ? "Saving..." : "Create Category"}
            </button>
          </div>

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

/* ---------- Reusable Fields ---------- */

const Input = ({ label, ...props }) => (
  <div>
    <label className="block text-sm font-medium text-gray-600 mb-1">
      {label}
    </label>
    <input
      {...props}
      className="w-full rounded-xl border px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
    />
  </div>
);

const Textarea = ({ label, rows = 4, ...props }) => (
  <div>
    <label className="block text-sm font-medium text-gray-600 mb-1">
      {label}
    </label>
    <textarea
      {...props}
      rows={rows}
      className="w-full rounded-xl border px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none resize-none"
    />
  </div>
);

const Select = ({ label, options, loading, ...props }) => (
  <div>
    <label className="block text-sm font-medium text-gray-600 mb-1">
      {label}
    </label>
    <select
      {...props}
      className="w-full rounded-xl border px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
    >
      <option value="">Main Category</option>
      {loading ? (
        <option>Loading...</option>
      ) : (
        options.map((cat) => (
          <option key={cat.id} value={cat.id}>
            {"—".repeat(cat.level)} {cat.name}
          </option>
        ))
      )}
    </select>
  </div>
);

export default AddCategoryPage;
