import React, { useState } from "react";
import { ICONS } from "../../icons";
import "./TOD.IconSelect.css";

const IconSelect = ({ value, onChange, label, category }) => {
  const [isOpen, setIsOpen] = useState(false);

  const availableIcons = category
    ? ICONS.filter((icon) => icon.category == category)
    : ICONS;

  const selectedIcon = availableIcons.find((icon) => icon.value == value);

  return (
    <div className="icon-select-container">
      {label && <label className="form-label">{label}</label>}

      <div className="icon-select-wrapper">
        <button
          type="button"
          className="icon-select-trigger"
          onClick={() => setIsOpen(!isOpen)}
        >
          {selectedIcon ? (
            <>
              <span className="icon-select-value">
                <selectedIcon.component />
                {selectedIcon.label}
              </span>
            </>
          ) : (
            <span className="icon-select-placeholder">Select an icon</span>
          )}
          <svg
            className={`icon-select-arrow ${isOpen ? "open" : ""}`}
            width="10"
            height="6"
            viewBox="0 0 10 6"
          >
            <path
              d="M1 1L5 5L9 1"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
            />
          </svg>
        </button>

        {isOpen && (
          <div className="icon-select-dropdown">
            {Object.entries(availableIcons).map(([key, icon]) => (
              <button
                key={key}
                type="button"
                className={`icon-select-option ${
                  value === key ? "selected" : ""
                }`}
                onClick={() => {
                  onChange(icon.value);
                  setIsOpen(false);
                }}
              >
                <icon.component />
                <span>{icon.label}</span>
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default IconSelect;
