import React, { useState, useEffect, useRef } from "react";
import "./TOD.IconPicker.css";

const ICONS_PER_PAGE = 50;

const IconPicker = ({ value, onChange, label, category = null }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [icons, setIcons] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [totalIcons, setTotalIcons] = useState(0);
  const [selectedIcon, setSelectedIcon] = useState(null);
  const pickerRef = useRef(null);
  const siteUrl = window.wb_onboard_vars.site_url;

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (pickerRef.current && !pickerRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  const loadIconsPage = async (pageNum, search = "") => {
    setLoading(true);
    try {
      const url = new URL(`${siteUrl}/wp-json/wb-onboard/v1/icons`);
      url.searchParams.append('page', pageNum);
      url.searchParams.append('per_page', ICONS_PER_PAGE);
      url.searchParams.append('search', search);
      if (category) {
        url.searchParams.append('category', category);
      }

      const response = await fetch(url);
      const data = await response.json();
      if (pageNum === 1) {
        setIcons(data.icons);
      } else {
        setIcons(prev => [...prev, ...data.icons]);
      }
      setTotalIcons(data.total);
    } catch (error) {
      console.error("Error loading icons:", error);
    }
    setLoading(false);
  };

  // Charger une icône spécifique
  const loadSpecificIcon = async (iconValue) => {
    if (!iconValue) return;

    setLoading(true);
    try {
      const url = new URL(`${siteUrl}/wp-json/wb-onboard/v1/icons`);
      url.searchParams.append('icon', iconValue);
      if (category) {
        url.searchParams.append('category', category);
      }

      const response = await fetch(url);
      const data = await response.json();
      if (data.icon) {
        setSelectedIcon(data.icon);
      }
    } catch (error) {
      console.error("Error loading specific icon:", error);
    }
    setLoading(false);
  };

  // Charger l'icône initiale si une value existe
  useEffect(() => {
    if (value) {
      loadSpecificIcon(value);
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      loadIconsPage(1, searchTerm);
    }
  }, [isOpen, searchTerm]);

  const handleSearch = (e) => {
    setSearchTerm(e.target.value);
    setPage(1);
  };

  const loadMore = () => {
    const nextPage = page + 1;
    setPage(nextPage);
    loadIconsPage(nextPage, searchTerm);
  };

  const handleSelectIcon = (icon) => {
    setSelectedIcon(icon);
    onChange(icon.value);
    setIsOpen(false);
  };

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

      <div className="icon-picker-wrapper">
        <button
          type="button"
          className="icon-picker-trigger"
          onClick={() => setIsOpen(!isOpen)}
        >
          {selectedIcon ? (
            <img src={selectedIcon.path} alt={selectedIcon.value} className="icon-preview" />
          ) : (
            <span className="icon-picker-placeholder">Choose an icon</span>
          )}
        </button>

        {isOpen && (
          <div className="icon-picker-popup">
            <div className="icon-picker-search">
              <input
                type="text"
                placeholder="Search icons..."
                value={searchTerm}
                onChange={handleSearch}
              />
            </div>

            <div className="icon-picker-grid">
              {icons.map((icon) => (
                <button
                  key={icon.value}
                  type="button"
                  className={`icon-picker-option ${selectedIcon?.value === icon.value ? "selected" : ""}`}
                  onClick={() => handleSelectIcon(icon)}
                >
                  <img src={icon.path} alt={icon.value} />
                </button>
              ))}
            </div>

            {icons.length < totalIcons && !loading && (
              <button
                className="icon-picker-load-more"
                onClick={loadMore}
              >
                Load more icons
              </button>
            )}

            {loading && <div className="icon-picker-loading">Loading...</div>}
          </div>
        )}
      </div>
    </div>
  );
};

export default IconPicker;
