"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import ToastMessage from "@/components/common/ToastMessage";
import { Trash } from "lucide-react";
import Tiptap from "@/components/TipTap/tiptap";
import axios from "axios";
import SpecificationForm from "../custom ui/specsForm";
import FilterSpecsForm from "../custom ui/filterForm";

interface CategoriesFormProps {
  initialData?: CategoryType | null;
}

const CategoriesForm: React.FC<CategoriesFormProps> = ({ initialData }) => {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [name, setName] = useState("");
  const [category_type, setCategoryType] = useState("MAIN_CATEGORY");
  const [parent, setParent] = useState("");
  const [description, setDescription] = useState("");
  const [categories, setCategories] = useState<CategoryType[]>([]);
  const [categoriesArray, setCategoriesArray] = useState<CategoryType[]>([]);
  const [specifications, setSpecifications] = useState<string | JSON>("");


  const fetchCategories = async () => {
    const response = await fetch("/api/admin/categories");
    const data = await response.json();
    setCategories(data.data);
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  useEffect(() => {
    if (initialData && categories.length > 0) {
      // SET INITIAL DATA HERE
      setName(initialData.name);
      setDescription(initialData.description || "");
      setCategoryType(initialData.category_type);
      setSpecifications(initialData.filters || "");

      var type: string | null;

      if (initialData.category_type === ("MAIN_CATEGORY" as string)) {
        type = null;
      } else if (initialData.category_type === ("SUB_CATEGORY" as string)) {
        type = "MAIN_CATEGORY";
      } else {
        type = "SUB_CATEGORY";
      }

      const array = categories.filter(
        (category) => category.category_type === type
      );
      setCategoriesArray(array);

      // console.log(`PARENT - ${initialData.parent_id}`);

      setParent(initialData.parent_id);

    }
  }, [initialData, categories]);

  const onSubmit = async (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    setLoading(true);
    const apiUrl = initialData
      ? `/api/admin/categories/${initialData.uuid}`
      : "/api/admin/categories";

    if (
      name === "" ||
      description === "" ||
      category_type === "" ||
      (parent === "" && category_type !== "MAIN_CATEGORY")
    ) {
      ToastMessage("Missing fields", "error");
      setLoading(false);
      return;
    }

    const formData = new FormData();
    formData.append("name", name);
    formData.append("description", description);
    formData.append("category_type", category_type);
    formData.append("parent", parent);

    console.log(typeof specifications)

    formData.append("specifications", specifications.toString())

    
    var response;

    if (initialData) {
      response = await axios.put(apiUrl, formData);
    } else {
      response = await axios.post(apiUrl, formData);
    }

    if (response.status == 200) {
      initialData
        ? ToastMessage("Category updated successfully", "success")
        : ToastMessage("Category created successfully", "success");
      router.push("/admin/categories");
    } else {
      initialData
        ? ToastMessage("Category update failed", "error")
        : ToastMessage("Category creation failed", "error");
    }

    setLoading(false);
  };

  const handleCategoryType = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setCategoryType(e.target.value);

    if (e.target.value === "MAIN_CATEGORY") {
      setParent("");
      setCategoriesArray([]);
    } else if (e.target.value === "SUB_CATEGORY") {
      setParent("");
      setCategoriesArray(
        categories.filter(
          (category) => category.category_type === ("MAIN_CATEGORY" as string)
        )
      );
    } else {
      setParent("");
      setCategoriesArray(
        categories.filter(
          (category) => category.category_type === ("SUB_CATEGORY" as string)
        )
      );
    }
  };

  return (
    <div className="mx-auto bg-white rounded-2xl shadow-md p-6 space-y-8">
      <div className="flex items-center justify-between border-b pb-4">
        <h1 className="text-2xl font-bold text-gray-800">
          {initialData ? "Edit Category" : "Add New Category"}
        </h1>
        {initialData && (
          <Button
            onClick={() => {
              if (confirm("Are you sure you want to delete this category?")) {
                axios
                  .delete(`/api/admin/categories/${initialData?.uuid}`)
                  .then((response) => {
                    if (response.status === 200) {
                      ToastMessage("Category deleted successfully", "success");
                      router.push("/admin/categories");
                    } else {
                      ToastMessage("Category deletion failed", "error");
                    }
                  });
              }
            }}
            className="flex items-center justify-center bg-red-600 hover:bg-red-700 text-white rounded-full p-3 shadow-md transition duration-300"
          >
            <Trash size={20} />
          </Button>
        )}
      </div>

      <form className="space-y-6">
        <div>
          <label htmlFor="name" className="block text-sm font-semibold text-gray-700 mb-2">
            Name
          </label>
          <input
            value={name}
            type="text"
            name="name"
            placeholder="Enter category name"
            onChange={(e) => setName(e.target.value)}
            required
            className="w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
          />
        </div>

        <div>
          <label htmlFor="description" className="block text-sm font-semibold text-gray-700 mb-2">
            Description
          </label>
          <div className="border rounded-lg shadow-sm p-2">
            <Tiptap content={description} onUpdate={(newContent) => setDescription(newContent)} />
          </div>
        </div>

        <div>
          <label htmlFor="category_type" className="block text-sm font-semibold text-gray-700 mb-2">
            Category Type
          </label>
          <select
            value={category_type}
            onChange={(e) => handleCategoryType(e)}
            name="category_type"
            className="w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
            required
          >
            <option value="MAIN_CATEGORY">Main Category</option>
            <option value="SUB_CATEGORY">Sub Category</option>
            <option value="SUB_SUB_CATEGORY">Sub Sub Category</option>
          </select>
        </div>

        <div>
          <label htmlFor="parent" className="block text-sm font-semibold text-gray-700 mb-2">
            Parent
          </label>
          <select
            value={parent}
            name="parent_id"
            onChange={(e) => setParent(e.target.value)}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
            required={category_type !== "MAIN_CATEGORY"}
          >
            <option value="">Select Parent</option>
            {categoriesArray &&
              categoriesArray.map((category) => (
                <option key={category.uuid} value={category.id}>
                  {category.name}
                </option>
              ))}
          </select>
        </div>

        {/* Specifications */}
        <div className="col-span-full">
          <FilterSpecsForm
            content={specifications}
            onUpdate={(newContent: string | JSON) =>
              setSpecifications(newContent)
            }
          />
        </div>

        <div className="flex gap-4 pt-4">
          <Button
            onClick={(e) => onSubmit(e)}
            disabled={loading}
            className="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg shadow-md transition"
          >
            {loading ? "Saving..." : "Submit"}
          </Button>
          <Button
            type="button"
            variant="secondary"
            onClick={() => router.push("/admin/categories")}
            className="px-6 py-2 rounded-lg shadow-md"
          >
            Discard
          </Button>
        </div>
      </form>
    </div>
  );

};

export default CategoriesForm;
