import React, { useState, useEffect } from "react";
import Link from "next/link";
import Cookies from "js-cookie";
import apiInterceptor from "@/interceptor/interceptor";
import { categoryInterface } from "@/INTERFACES/category";
import { subCategoryInterface } from "@/INTERFACES/subCategory";
import { attributeInterface } from "@/INTERFACES/attributeInterface";
import { variationInterface } from "@/INTERFACES/variationInterface";
import { userActivity } from "@/components/commonFunctions/userActivity";
import jwt from "jsonwebtoken";

const Index = () => {
  const token: any = Cookies.get("jazz_admin_token");

  const decodedToken = jwt.decode(token);

  const userId = decodedToken ? decodedToken.sub : null;  const [categories, setCategories] = useState<categoryInterface[]>([]);
  const [subCategories, setSubCategories] = useState<subCategoryInterface[]>(
    []
  );
  const [attributes, setAttributes] = useState<attributeInterface[]>([]);
  const [variations, setVariations] = useState<variationInterface[]>([]);

  const [selectedCategoryId, setSelectedCategoryId] = useState<string>("");
  const [selectedSubCategoryId, setSelectedSubCategoryId] =
    useState<string>("");
  const [selectedAttributeId, setSelectedAttributeId] = 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);
    };
    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}`,
          },
        }
      );
      console.log("attribute data", response.data.attributes);
      setAttributes(response.data.attributes);
    } catch (error) {
      console.error("Error:", error);
    }
  };

  useEffect(() => {
    if (selectedCategoryId && selectedSubCategoryId) {
      getAttributes();
    } else {
      setAttributes([]);
    }
  }, [selectedCategoryId, selectedSubCategoryId]);

  // Variation

  const getVariations = async () => {
    try {
      const accessToken = Cookies.get("jazz_token");
      const variationResponse = await apiInterceptor.get(
        `/api/getVariations/${selectedAttributeId}`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        }
      );
      setVariations(variationResponse.data.variations);
      console.log("variation List", variationResponse.data.variations);
    } catch (error) {
      console.error("Error", error);
    }
  };

  useEffect(() => {
    if(selectedAttributeId){
      getVariations();
    }else{
      setVariations([])
    }
  }, [selectedAttributeId]);

  const handleDelete = async (variationId: string) => {
    const accessToken = Cookies.get("jazz_token");
    await apiInterceptor.delete(`/api/admin/variations/${variationId}`, {
      headers: {
        authorization: `Bearer ${accessToken}`,
      },
    });
    setVariations((prevData) =>
      prevData.filter((item) => item._id !== variationId)
    );
  };

  return (
    <div className="flex flex-col p-8">

      <Link
        className="ml-[4rem] lg:ml-4 px-3 mx-4 rounded transition-all duration-300 py-2 hover:bg-[#FE342B] bg-[#383736] max-w-fit text-white my-2"
        href={"/admin/variations/addVariations"}
        onClick={() => {
          if (userId) {
            userActivity(
              userId,
              "admin",
              "Add New Variation",
              {
                pageVisit: `/`,
              },
              navigator.userAgent
            );
          } else {
            console.error("User ID is not available");
          }
        }}
      >
        Add New Variation
        </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 selected 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 className="mb-4">
            <label
              htmlFor="attributeId"
              className="block mb-2 text-sm font-medium text-[#FF332B] "
            >
              Attribute
            </label>
            <select
              id="attributeId"
              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={selectedAttributeId}
              onChange={(e) => setSelectedAttributeId(e.target.value)}
            >
              <option disabled value="">
                Select Attribute
              </option>
              {attributes
                .filter((item) => item.subCategoryId === selectedSubCategoryId)
                .map((item) => (
                  <option value={item._id} key={item._id}>
                    {item.attributeName}
                  </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">VARIATION</th>
                  <th className=" py-4 text-right px-[2rem]">Action</th>
                </tr>
              </thead>
              {variations.map((item, index) => (
                <tbody key={item._id}>
                  <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.variationName}
                    </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/variations/update-variations/${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;
