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">
  {/* Category */}
  <div>
    <label className="block mb-2 text-sm font-medium text-[#FF332B]">Category</label>
    <select
      id="categoryId"
      className="shadow-sm focus:outline-none bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg block w-full p-2.5"
      value={selectedCategoryId}
      onChange={(e) => {
        setSelectedCategoryId(e.target.value);
        setSelectedSubCategoryId(""); // Reset child dropdowns
        setSelectedAttributeId("");
      }}
    >
      <option value="" disabled>Select Category</option>
      {categories.map((item: any) => (
        <option value={item.id || item.id} key={item.id || item.id}>
          {item.categoryName}
        </option>
      ))}
    </select>
  </div>

  {/* Subcategory - FIXED FILTER */}
  <div>
    <label className="block mb-2 text-sm font-medium text-[#FF332B]">Subcategory</label>
    <select
      id="subCategoryId"
      className="shadow-sm focus:outline-none bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg block w-full p-2.5"
      value={selectedSubCategoryId}
      onChange={(e) => {
        setSelectedSubCategoryId(e.target.value);
        setSelectedAttributeId("");
      }}
    >
      <option value="" disabled>Select Subcategory</option>
      {subCategories
        .filter((item: any) => String(item.categoryId || item.category_id) === String(selectedCategoryId))
        .map((item: any) => (
          <option value={item.id || item.id} key={item.id || item.id}>
            {item.subCategoryName}
          </option>
        ))}
    </select>
  </div>

  {/* Attribute */}
  <div>
    <label className="block mb-2 text-sm font-medium text-[#FF332B]">Attribute</label>
    <select
      id="attributeId"
      className="shadow-sm focus:outline-none bg-gray-50 border border-gray-300 text-[#FF332B] text-sm rounded-lg block w-full p-2.5"
      value={selectedAttributeId}
      onChange={(e) => setSelectedAttributeId(e.target.value)}
    >
      <option value="" disabled>Select Attribute</option>
      {attributes.map((item: any) => (
        <option value={item.id || item.id} key={item.id || 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;
