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: "",
    image: "",
    metaTitle: "",
    metaDescription: "",
  });

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await updateCategory({ id, ...form }).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="max-w-3xl mx-auto space-y-6">
      {/* Back Link */}
      <div className="flex items-center space-x-2 text-blue-600 hover:text-blue-800">
        <ArrowLeft size={18} />
        <Link to="/categories" className="font-medium">
          Back to Categories
        </Link>
      </div>

      {/* Form */}
      <div className="bg-white rounded-xl shadow-md p-6 border">
        <h2 className="text-2xl font-bold mb-6">Edit Category</h2>

        <form className="space-y-4" onSubmit={handleSubmit}>
          <FormInput
            label="Name"
            name="name"
            value={form.name}
            onChange={handleChange}
            required
          />
          <FormInput
            label="Description"
            name="description"
            value={form.description}
            onChange={handleChange}
          />
          <FormInput
            label="Image URL"
            name="image"
            value={form.image}
            onChange={handleChange}
          />
          <FormInput
            label="Meta Title"
            name="metaTitle"
            value={form.metaTitle}
            onChange={handleChange}
          />
          <FormInput
            label="Meta Description"
            name="metaDescription"
            value={form.metaDescription}
            onChange={handleChange}
          />

          <button
            type="submit"
            disabled={isUpdating}
            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition"
          >
            {isUpdating ? "Updating..." : "Update Category"}
          </button>
        </form>
      </div>
    </div>
  );
};

const FormInput = ({ label, name, value, onChange, required }) => (
  <div>
    <label className="block text-gray-700 font-medium mb-1">{label}</label>
    <input
      type="text"
      name={name}
      value={value}
      onChange={onChange}
      required={required}
      className="w-full border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
    />
  </div>
);

export default CategoryEdit;
