import React, { useState, useEffect, useMemo, useCallback } from "react";
import { useDecalStore } from "../../../../store/builder/store";
import { getFilteredAssets } from "./assetsHelpers/filteredAssetsHelper";
import { fetchCategoryDecals } from "./assetsHelpers/fetchDecalsHelper";
import {
  fetchAllAssets,
  fetchCategoryAssets,
} from "./assetsHelpers/fetchAssetsHelper";
import Search from "../../../ui/inputs/Search";
import SkeletonUI from "../../../templates/SkeletonUI";
import { RenderAsset } from "./assetsHelpers/renderAssetHelper";
import {
  ACTIVE_DECAL_SUBCATEGORIES,
  CATEGORY_LIST,
} from "./assetsHelpers/constants";
import { ArrowIcon } from "../../../icons/ExportCommonIcons";

const Assets: React.FC = () => {
  const { selectedSubCategory, setSelectedSubCategory } = useDecalStore();
  const [searchValue, setSearchValue] = useState<string | null>(null);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [assets, setAssets] = useState<AssetProp[] | DecalProp[]>([]);
  const [globalResults, setGlobalResults] = useState<(AssetProp | DecalProp)[]>(
    []
  );
  const [isLoading, setIsLoading] = useState(false);

  const filteredAssets = useMemo(
    () =>
      getFilteredAssets({
        assets,
        searchValue,
        selectedCategory,
        selectedSubCategory,
      }),
    [assets, searchValue, selectedCategory, selectedSubCategory]
  );

  const handleFetchCategory = useCallback(
    async (category: string) => {
      setIsLoading(true);
      setSelectedCategory(category);
      if (category === "Decals") {
        const res = await fetchCategoryDecals("Safety");
        setAssets(res);
        setSelectedSubCategory("Safety");
      } else {
        const res = await fetchCategoryAssets(category);
        setAssets(res);
      }
      setIsLoading(false);
    },
    [setSelectedSubCategory]
  );

  const fetchGlobalSearch = useCallback(async (term: string) => {
    setIsLoading(true);
    const allAssets = await fetchAllAssets();
    const lowerTerm = term.toLowerCase();
    const matches = allAssets.filter(
      (a) =>
        a.filename.toLowerCase().includes(lowerTerm) ||
        a.tags?.toLowerCase().includes(lowerTerm) ||
        a.category?.toLowerCase().includes(lowerTerm)
    );
    setGlobalResults(matches);
    setIsLoading(false);
  }, []);

  useEffect(() => {
    if (!selectedCategory && searchValue?.trim())
      fetchGlobalSearch(searchValue);
    else setGlobalResults([]);
  }, [searchValue, selectedCategory, fetchGlobalSearch]);

  return (
    <div className="assets-container-main">
      <Search debounced onChange={setSearchValue} value={searchValue} />
      <div className="assets-list-section">
        <section>
          {isLoading ? (
            <SkeletonUI type="asset" />
          ) : searchValue || selectedCategory ? (
            <div className="assets-wrapper">
              {selectedCategory ? (
                <>
                  <h2 className="header">
                    {selectedCategory}
                    <button
                      className="back-button"
                      onClick={() => {
                        setSelectedCategory(null);
                        setSelectedSubCategory(null);
                        setAssets([]);
                        setSearchValue(null);
                      }}
                    >
                      <div className="back-arrow">
                        <ArrowIcon />
                      </div>{" "}
                      Back
                    </button>
                  </h2>
                  {selectedCategory === "Decals" && (
                    <div className="catogory-asset-filter">
                      {ACTIVE_DECAL_SUBCATEGORIES.map((cat) => (
                        <div
                          key={cat.name}
                          className={`catogory-asset-filter-wrapper ${
                            selectedSubCategory === cat.name ? "active" : ""
                          }`}
                          onClick={async () => {
                            setIsLoading(true);
                            const res = await fetchCategoryDecals(cat.name);
                            setAssets(res);
                            setSelectedSubCategory(cat.name);
                            setIsLoading(false);
                          }}
                        >
                          <div className="sub-catagory">{cat.icon}</div>
                          <div className="sub-catagory">{cat.name}</div>
                        </div>
                      ))}
                    </div>
                  )}
                  <div className="assets-container">
                    {filteredAssets.map((a, i) => (
                      <RenderAsset key={i} asset={a} index={i} />
                    ))}
                    {filteredAssets.length === 0 && (
                      <div className="no-asset">🚧 No assets found</div>
                    )}
                  </div>
                </>
              ) : (
                <>
                  <h2 className="header">Global Search Results</h2>
                  <div className="assets-container">
                    {globalResults.map((a, i) => (
                      <RenderAsset key={i} asset={a} index={i} />
                    ))}
                    {globalResults.length === 0 && (
                      <div className="no-asset">🔎 No matches found</div>
                    )}
                  </div>
                </>
              )}
            </div>
          ) : (
            <div className="assets-wrapper">
              <h2 className="categories-header">Categories</h2>
              <div className="categories-container">
                {CATEGORY_LIST.map((cat) => (
                  <div
                    key={cat.category}
                    className="category"
                    onClick={() => handleFetchCategory(cat.category)}
                  >
                    <img
                      src={cat.categoryImage}
                      alt={cat.category}
                      className="category-image"
                      draggable={false}
                    />
                    <div className="category-name">{cat.category}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </section>
      </div>
    </div>
  );
};

export default Assets;
