"use client";

import cx from "classnames";
import { useEffect, useState } from "react";

import { Bar, BarItem, Button, Container, Label } from "..";
import { handleSvgClick, loadIconNames } from "./iconUtils";
import { Pictogram } from "./Pictogram";

// Pictogram names will be loaded dynamically on the client
let pictogramNamesCache = [];

const getPictogramNames = () => {
  if (typeof window !== "undefined" && pictogramNamesCache.length === 0) {
    const requireContext = require.context(
      "../../assets/icons",
      false,
      /\.svg$/,
    );
    pictogramNamesCache = loadIconNames(
      requireContext,
      (name) => name.startsWith("pictogram-") && !name.endsWith("--dark"),
    );
  }
  return pictogramNamesCache;
};

export { getPictogramNames };

export const PictogramList = ({ pictograms, isWide = true }) => (
  <ul className={cx("sg-icon-list", { "sg-icon-list--wide": isWide })}>
    {pictograms.map(({ name, description, size = "xlarge", ...other }, i) => {
      return (
        <li className="sg-icon-list__item" key={i.toString()} id={name}>
          <Pictogram
            name={name}
            size={size}
            onClick={(e) => handleSvgClick(e.currentTarget, "pictogram")}
            {...other}
          />
          <br />
          <abbr title={description || name}>{description || name}</abbr>
        </li>
      );
    })}
  </ul>
);

export const PictogramSearch = () => {
  const [searchValue, setSearchValue] = useState("");
  const [allPictograms, setAllPictograms] = useState([]);
  const [filteredPictograms, setFilteredPictograms] = useState([]);

  // Load pictograms on mount (client-side only)
  useEffect(() => {
    if (typeof window !== "undefined") {
      const pictogramNames = getPictogramNames();
      const pictogramsData = pictogramNames.map((name) => ({
        size: "xxlarge",
        name,
        id: name,
      }));
      setAllPictograms(pictogramsData);
      setFilteredPictograms(pictogramsData);
    }
  }, []);

  // Filter pictograms based on search criteria
  useEffect(() => {
    if (!allPictograms.length) return;

    let filtered = allPictograms.filter((pictogram) => {
      // Filter by search value - search in pictogram name
      return !searchValue || pictogram.name.includes(searchValue);
    });

    setFilteredPictograms(filtered);
  }, [allPictograms, searchValue]);

  const handleInputChange = (value) => {
    setSearchValue(value);
  };

  const handleClear = () => {
    setSearchValue("");
  };

  return (
    <Container>
      <Bar space="small" className="align-items-end">
        <BarItem>
          <div className="form-field">
            <Label htmlFor={"pictogram-search-input"}>
              <h3 className="mb-xsmall">Search input</h3>
            </Label>
            <input
              className="text-input"
              onChange={(e) => handleInputChange(e.target?.value)}
              id="pictogram-search-input"
              value={searchValue}
            />
          </div>
        </BarItem>
        <BarItem isFilling>
          <Button
            type="primary"
            onClick={handleClear}
            isDisabled={!searchValue}
          >
            Clear
          </Button>
        </BarItem>
      </Bar>
      <div className="results">
        {allPictograms.length > 0 ? (
          <PictogramList pictograms={filteredPictograms} />
        ) : (
          <div>Loading pictograms...</div>
        )}
      </div>
    </Container>
  );
};
