import React, { useState, useEffect } from "react";
import Link from "next/link";
import Cookies from "js-cookie";
import apiInterceptor from "@/interceptor/interceptor";

import { Category } from "@/components/common/types/adminTypes";
import { SubCategory } from "@/components/common/types/adminTypes";
import { Attribute } from "@/components/common/types/adminTypes";

import { userActivity } from "@/components/commonFunctions/userActivity";
import { useRouter } from "next/router";
import jwt from "jsonwebtoken";



const Index: React.FC = () => {

  
  const token: any = Cookies.get("jazz_admin_token");

  const decodedToken = jwt.decode(token);

  const userId = decodedToken ? decodedToken.sub : null;
  const [attributes, setAttributes] = useState<Attribute[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [subCategories, setSubCategories] = useState<SubCategory[]>([]);

  const [selectedCategoryId, setSelectedCategoryId] = useState<string>("");
  const [selectedSubCategoryId, setSelectedSubCategoryId] =
    useState<string>("");

  useEffect(() => {
    const getAllCategoryDropdowns = async () => {
      const accessToken = Cookies.get("jazz_token");
      const categoryResponse = await apiInterceptor.get(
        `/api/admin/category?per_page=100`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      setCategories(categoryResponse.data.categories.data);
      // console.log("Fetched Categories:", categoryResponse.data.categories.data);
    };

    getAllCategoryDropdowns();
  }, []);

  useEffect(() => {
    const getAllSubCategoryDropdowns = async () => {
      const accessToken = Cookies.get("jazz_token");
      const subCategoryResponse = await apiInterceptor.get(
        `/api/admin/subCategory?per_page=500`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      setSubCategories(subCategoryResponse.data.subCategories.data);
    };
    getAllSubCategoryDropdowns();
  }, []);

  const getAttributes = async () => {
    try {
      const accessToken = Cookies.get("jazz_token");
      const response = await apiInterceptor.get(
        `/api/getAttributes?categoryId=${selectedCategoryId}&subCategoryId=${selectedSubCategoryId}`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );

      setAttributes(response.data.attributes);
    } catch (error) {
      console.error("Error:", error);
    }
  };

  useEffect(() => {
    if (selectedCategoryId && selectedSubCategoryId) {
      getAttributes();
    } else {
      setAttributes([]);
    }
  }, [selectedCategoryId, selectedSubCategoryId]);

  // const handleDelete = async (attributeId: string) => {
  //   try {
  //     const accessToken = Cookies.get("jazz_token");
  //     await axios.delete(
  //       `https://api.jazzagain.com/public/index.php/api/admin/attributes/${attributeId}`,
  //       {
  //         headers: {
  //           authorization: `Bearer ${accessToken}`,
  //         },
  //       }
  //     );
  //     // Update the state to remove the deleted category
  //     setAttributes((prevData) =>
  //       prevData.filter((item) => item._id !== attributeId)
  //     );
  //   } catch (error) {
  //     console.error("Error Deleting Brand:", error);
  //   }
  // };

  const handleDelete = async (attributeId: string) => {
    try {
      const accessToken = Cookies.get("jazz_token");

      const response = await apiInterceptor.delete(
        `/api/admin/attributes/${attributeId}`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );

      console.log(response);

      if (response.status === 201) {
        setAttributes((prevData) =>
          prevData.filter((item) => item._id !== attributeId)
        );
      } else {
        console.error("Failed to delete attribute");
      }
    } catch (error) {
      console.error("Error Deleting Attribute:", error);
    }
  };

  return (
    <div className="flex flex-col p-8">


<Link
             className="ml-[4rem] lg:ml-4 px-3 py-2 mx-4 rounded transition-all duration-300 hover:bg-[#FE342B] bg-[#383736] max-w-fit text-white my-2"
             href={"/admin/attributes/addAttributes"}
             onClick={() => {
              if (userId) {
                userActivity(
                  userId,
                  "admin",
                  "Add New Attributes",
                  {
                    pageVisit: `/`,
                  },
                  navigator.userAgent
                );
              } else {
                console.error("User ID is not available");
              }
            }}
      
      >
        Add New Attributes
        </Link>


      <form action="#" className="space-y-8 m-4 max-w-sm">
        <div className="space-y-8">
          <div>
            <label
              htmlFor="categoryId"
              className="block mb-2 text-sm font-medium text-[#FF332B] "
            >
              Category
            </label>
            <select
              id="categoryId"
              required
              className="shadow-sm focus:outline-none bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 "
              value={selectedCategoryId}
              onChange={(e) => setSelectedCategoryId(e.target.value)}
            >
              <option disabled value="">
                Select Category
              </option>
              {categories.map((item) => (
                <option value={item._id} key={item._id}>
                  {item.categoryName}
                </option>
              ))}
            </select>
          </div>

          <div className="mb-4">
            <label
              htmlFor="subCategoryId"
              className="block mb-2 text-sm font-medium text-[#FF332B] "
            >
              Subcategory
            </label>
            <select
              id="subCategoryId"
              required
              className="shadow-sm focus:outline-none bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 "
              value={selectedSubCategoryId}
              onChange={(e) => setSelectedSubCategoryId(e.target.value)}
            >
              <option disabled value="">
                Select Subcategory
              </option>
              {subCategories
                .filter((item) => item.categoryId === selectedCategoryId)
                .map((item) => (
                  <option value={item._id} key={item._id}>
                    {item.subCategoryName}
                  </option>
                ))}
            </select>
          </div>
        </div>
      </form>

      <div className="overflow-x-auto sm:-mx-6 lg:-mx-8">
        <div className="inline-block min-w-full py-2 sm:px-6 lg:px-8">
          <div className="overflow-hidden">
            <table className="min-w-full text-left text-sm font-light">
              <thead className="border-b bg-white font-medium">
                <tr>
                  <th className="px-6 py-4">#</th>
                  <th className="px-6 py-4">ATTRIBUTES</th>
                  <th className=" py-4 text-right px-[2rem]">Action</th>
                </tr>
              </thead>

              {attributes.map((item, index) => (
                <tbody key={item._id}>
                  {selectedCategoryId && selectedSubCategoryId && (
                    <tr className="border-b bg-neutral-100 dark:border-neutral-500 hover:bg-gray-200">
                      <td className="whitespace-nowrap px-6 py-4 font-medium">
                        {index + 1}
                      </td>
                      <td className="whitespace-nowrap px-6 py-4">
                        {item.attributeName}
                      </td>
                      <td className="whitespace-nowrap px-6 py-4 flex-row-reverse flex">
                        <button
                          onClick={() => handleDelete(item._id)}
                          className="bg-[#FE342B] hover:bg-[#d13931] rounded text-white px-3 py-2 mx-2"
                        >
                          Delete
                        </button>
                        <Link
                          href={`/admin/attributes/update-attributes/${item._id}`}
                          className="bg-[#383736] hover:bg-[#2d2d2c] rounded text-white px-3 py-2 mx-2"
                        >
                          Update
                        </Link>
                      </td>
                    </tr>
                  )}
                </tbody>
              ))}
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Index;
