import React, { useEffect, useState } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import { ArrowLeft } from "lucide-react";
import {
  useGetCategoryByIdQuery,
  useUpdateCategoryMutation,
} from "../../features/categories/categoryAPI";

const CategoryEdit = () => {
  const { id } = useParams();
  const navigate = useNavigate();

  const { data, isLoading } = useGetCategoryByIdQuery(id);
  const [updateCategory, { isLoading: isUpdating }] =
    useUpdateCategoryMutation();

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

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

  useEffect(() => {
    if (data?.data) {
      const { name, description, image, metaTitle, metaDescription } =
        data.data;

      setForm({ name, description, metaTitle, metaDescription });
      setPreviewImage(image); // show existing image
    }
  }, [data]);

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

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

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

    try {
      const formData = new FormData();

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

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

      await updateCategory({ id, data: formData }).unwrap();

      alert("Category updated successfully!");
      navigate("/categories");
    } catch (error) {
      console.error(error);
      alert("Failed to update category");
    }
  };

  if (isLoading) {
    return <div className="text-center py-10">Loading category...</div>;
  }

  return (
    <div className="min-h-screen bg-gray-200 py-12 px-4">
      <div className="max-w-5xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-10">
          <Link
            to="/categories"
            className="flex items-center gap-2 text-gray-600 hover:text-indigo-600 transition"
          >
            <ArrowLeft size={20} />
            <span className="font-medium">Back to Categories</span>
          </Link>

          <h1 className="text-xl font-bold bg-gradient-to-r from-indigo-600 to-blue-600 bg-clip-text text-transparent">
            Edit Category
          </h1>
        </div>

        {/* Glass Card */}
        <div className="backdrop-blur-xl bg-white/70 border border-white/40 shadow-2xl rounded-3xl p-10 transition hover:shadow-indigo-200/50">
          <form className="space-y-10" onSubmit={handleSubmit}>
            {/* SECTION 1 */}
            <div>
              <h2 className="text-xl font-semibold text-gray-800 mb-6">
                Basic Information
              </h2>

              <div className="grid md:grid-cols-2 gap-8">
                <FloatingInput
                  label="Category Name"
                  name="name"
                  value={form.name}
                  onChange={handleChange}
                  required
                />

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

              <div className="mt-8 space-y-6">
                <FloatingTextarea
                  label="Description"
                  name="description"
                  value={form.description}
                  onChange={handleChange}
                />

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

            {/* SECTION 2 - IMAGE */}
            <div>
              <h2 className="text-xl font-semibold text-gray-800 mb-6">
                Category Image
              </h2>

              <div className="flex flex-col md:flex-row items-start gap-10">
                {/* Preview Card */}
                <div className="relative group w-56 h-56 rounded-2xl overflow-hidden shadow-xl border border-gray-200">
                  {previewImage ? (
                    <>
                      <img
                        src={previewImage}
                        alt="Preview"
                        className="w-full h-full object-cover transition duration-300 group-hover:scale-110"
                      />
                      <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center text-white font-medium transition">
                        Change Image
                      </div>
                    </>
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-gray-400 bg-gray-100">
                      No Image
                    </div>
                  )}
                </div>

                {/* Upload Button */}
                <label className="cursor-pointer">
                  <div className="px-8 py-4 rounded-2xl bg-gradient-to-r from-indigo-500 to-blue-600 text-white font-semibold shadow-lg hover:shadow-xl hover:scale-105 transition-all duration-300">
                    Upload New Image
                  </div>
                  <input
                    type="file"
                    accept="image/*"
                    onChange={handleImageChange}
                    hidden
                  />
                </label>
              </div>
            </div>

            {/* Submit */}
            <div className="pt-6 border-t border-gray-200 flex justify-end">
              <button
                type="submit"
                disabled={isUpdating}
                className="px-10 py-4 rounded-2xl bg-gradient-to-r from-emerald-500 to-green-600 text-white font-semibold shadow-xl hover:scale-105 hover:shadow-2xl transition-all duration-300 disabled:opacity-50"
              >
                {isUpdating ? "Updating..." : "Update Category"}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

const FloatingInput = ({ label, name, value, onChange, required }) => (
  <div className="relative">
    <input
      type="text"
      name={name}
      value={value}
      onChange={onChange}
      required={required}
      placeholder=" "
      className="peer w-full border border-gray-300 rounded-xl px-4 pt-6 pb-2 bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition"
    />
    <label
      className="absolute left-4 top-2 text-gray-500 text-sm transition-all 
      peer-placeholder-shown:top-4 
      peer-placeholder-shown:text-base 
      peer-placeholder-shown:text-gray-400
      peer-focus:top-2 
      peer-focus:text-sm 
      peer-focus:text-indigo-600"
    >
      {label}
    </label>
  </div>
);

const FloatingTextarea = ({ label, name, value, onChange }) => (
  <div className="relative">
    <textarea
      name={name}
      value={value}
      onChange={onChange}
      rows={4}
      placeholder=" "
      className="peer w-full border border-gray-300 rounded-xl px-4 pt-6 pb-2 bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition resize-none"
    />
    <label
      className="absolute left-4 top-2 text-gray-500 text-sm transition-all 
      peer-placeholder-shown:top-4 
      peer-placeholder-shown:text-base 
      peer-placeholder-shown:text-gray-400
      peer-focus:top-2 
      peer-focus:text-sm 
      peer-focus:text-indigo-600"
    >
      {label}
    </label>
  </div>
);

export default CategoryEdit;
