import React, { useEffect, useState } from "react";
import Search from "../../ui/inputs/Search";
import { getCategoryAsset } from "../../../services/factoryBuilder/asset/assets/getCategoryAsset";
import { fetchAssets } from "../../../services/marketplace/fetchAssets";
import { useSelectedItem } from "../../../store/builder/store";

// images -------------------
import vehicle from "../../../assets/image/categories/vehicles.png";
import workStation from "../../../assets/image/categories/workStation.png";
import machines from "../../../assets/image/categories/machines.png";
import worker from "../../../assets/image/categories/worker.png";
import storage from "../../../assets/image/categories/storage.png";
import office from "../../../assets/image/categories/office.png";
import safety from "../../../assets/image/categories/safety.png";
import feneration from "../../../assets/image/categories/feneration.png";
import SkeletonUI from "../../templates/SkeletonUI";
// -------------------------------------

interface AssetProp {
  filename: string;
  thumbnail?: string;
  category: string;
  description?: string;
  tags: string;
  url?: string;
  uploadDate?: number;
  isArchieve?: boolean;
  animated?: boolean;
  price?: number;
  CreatedBy?: string;
}
interface CategoryListProp {
  assetImage?: string;
  assetName?: string;
  categoryImage: string;
  category: string;
}
const Assets: React.FC = () => {
  const { setSelectedItem } = useSelectedItem();
  const [searchValue, setSearchValue] = useState<string>("");
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [categoryAssets, setCategoryAssets] = useState<AssetProp[]>([]);
  const [filtereredAssets, setFiltereredAssets] = useState<AssetProp[]>([]);
  const [categoryList, setCategoryList] = useState<CategoryListProp[]>([]);
  const [isLoading, setisLoading] = useState<boolean>(false); // Loading state for assets

  const handleSearchChange = (value: string) => {
    const searchTerm = value.toLowerCase();
    setSearchValue(value);
    if (searchTerm.trim() === "" && !selectedCategory) {
      setCategoryAssets([]);
      return;
    }
    const filteredModels = filtereredAssets?.filter((model) => {
      if (!model?.tags || !model?.filename || !model?.category) return false;
      if (searchTerm.startsWith(":") && searchTerm.length > 1) {
        const tagSearchTerm = searchTerm.slice(1);
        return model.tags.toLowerCase().includes(tagSearchTerm);
      } else if (selectedCategory) {
        return (
          model.category
            .toLowerCase()
            .includes(selectedCategory.toLowerCase()) &&
          model.filename.toLowerCase().includes(searchTerm)
        );
      } else {
        return model.filename.toLowerCase().includes(searchTerm);
      }
    });

    setCategoryAssets(filteredModels);
  };

  useEffect(() => {
    const filteredAssets = async () => {
      try {
        const filt = await fetchAssets();
        setFiltereredAssets(filt);
      } catch {
        echo.error("Filter asset not found");
      }
    };
    filteredAssets();
  }, [categoryAssets]);

  useEffect(() => {
    setCategoryList([
      { category: "Fenestration", categoryImage: feneration },
      { category: "Vehicles", categoryImage: vehicle },
      { category: "Workstation", categoryImage: workStation },
      { category: "Machines", categoryImage: machines },
      { category: "Workers", categoryImage: worker },
      { category: "Storage", categoryImage: storage },
      { category: "Safety", categoryImage: safety },
      { category: "Office", categoryImage: office },
    ]);
  }, []);

  const fetchCategoryAssets = async (asset: any) => {
    setisLoading(true);
    setSelectedCategory(asset);
    try {
      const res = await getCategoryAsset(asset);
      setCategoryAssets(res);
      setFiltereredAssets(res);
      setisLoading(false); // End loading
      // eslint-disable-next-line
    } catch (error) {
      echo.error("failed to fetch assets");
      setisLoading(false);
    }
  };

  return (
    <div className="assets-container-main">
      <Search onChange={handleSearchChange} />
      <div className="assets-list-section">
        <section>
          {(() => {
            if (isLoading) {
              return <SkeletonUI type="asset" />; // Show skeleton when loading
            }
            if (searchValue) {
              return (
                <div className="assets-result">
                  <div className="assets-wrapper">
                    <div className="searched-content">
                      <p>Results for {searchValue}</p>
                    </div>
                    <div className="assets-container">
                      {categoryAssets?.map((asset: any, index: number) => (
                        <div
                          key={`${index}-${asset.filename}`}
                          className="assets"
                          id={asset.filename}
                          title={asset.filename}
                        >
                          <img
                            src={asset?.thumbnail}
                            alt={asset.filename}
                            className="asset-image"
                            onPointerDown={() => {
                              setSelectedItem({
                                name: asset.filename,
                                id: asset.AssetID,
                                type:
                                  asset.type === "undefined"
                                    ? undefined
                                    : asset.type
                              });
                            }}
                          />

                          <div className="asset-name">
                            {asset.filename
                              .split("_")
                              .map(
                                (word: any) =>
                                  word.charAt(0).toUpperCase() + word.slice(1)
                              )
                              .join(" ")}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              );
            }

            if (selectedCategory) {
              return (
                <div className="assets-wrapper">
                  <h2>
                    {selectedCategory}
                    <button
                      className="back-button"
                      id="asset-backButtom"
                      onClick={() => {
                        setSelectedCategory(null);
                        setCategoryAssets([]);
                      }}
                    >
                      ← Back
                    </button>
                  </h2>
                  <div className="assets-container">
                    {categoryAssets?.map((asset: any, index: number) => (
                      <div
                        key={`${index}-${asset}`}
                        className="assets"
                        id={asset.filename}
                        title={asset.filename}
                      >
                        <img
                          src={asset?.thumbnail}
                          alt={asset.filename}
                          className="asset-image"
                          onPointerDown={() => {
                            setSelectedItem({
                              name: asset.filename,
                              id: asset.AssetID,
                              type:
                                asset.type === "undefined"
                                  ? undefined
                                  : asset.type,
                              category: asset.category,
                              subCategory: asset.subCategory
                            });
                          }}
                        />
                        <div className="asset-name">
                          {asset.filename
                            .split("_")
                            .map(
                              (word: any) =>
                                word.charAt(0).toUpperCase() + word.slice(1)
                            )
                            .join(" ")}
                        </div>
                      </div>
                    ))}
                    {categoryAssets.length === 0 && (
                      <div className="no-asset">
                        🚧 The asset shelf is empty. We're working on filling it
                        up!
                      </div>
                    )}
                  </div>
                </div>
              );
            }

            return (
              <div className="assets-wrapper">
                <h2>Categories</h2>
                <div className="categories-container">
                  {Array.from(
                    new Set(categoryList.map((asset) => asset.category))
                  ).map((category, index) => {
                    const categoryInfo = categoryList.find(
                      (asset) => asset.category === category
                    );
                    return (
                      <div
                        key={`${index}-${category}`}
                        className="category"
                        id={category}
                        onClick={() => fetchCategoryAssets(category)}
                      >
                        <img
                          src={categoryInfo?.categoryImage ?? ""}
                          alt={category}
                          className="category-image"
                          draggable={false}
                        />
                        <div className="category-name">{category}</div>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })()}
        </section>
      </div>
    </div>
  );
};

export default Assets;
