import Widget from '../widgets/Widget'
import { useState, useMemo } from "@wordpress/element"
import '../../assets/scss/tabs.scss'

const WidgetTabs = ({
  addons,
  handleChange
}) => {
 
  // State to track the active tab. Persisted to localStorage so an accidental
  // page reload returns to the last selected tab instead of resetting to shop.
  const TAB_STORAGE_KEY = 'strb_widgets_active_tab';
  const [activeTab, setActiveTab] = useState(() => {
    try {
      return localStorage.getItem(TAB_STORAGE_KEY) || 'shop';
    } catch (e) {
      return 'shop';
    }
  });

  const selectTab = (cat) => {
    setActiveTab(cat);
    try {
      localStorage.setItem(TAB_STORAGE_KEY, cat);
    } catch (e) {
      // ignore storage failures (private mode / quota)
    }
  };
  const [query, setQuery] = useState('');
  const [view, setView] = useState('grid');
  const isProActive = Boolean(storebuild.is_pro_active)

  // Concept section icons per category (falls back to a generic glyph).
  const CAT_ICONS = {
    shop:       'M12 2 2 7l10 5 10-5-10-5Z|M2 17l10 5 10-5|M2 12l10 5 10-5',
    single:     'M2 5h20v14H2Z|M2 10h20',
    shopdetail: 'M2 5h20v14H2Z|M2 10h20',
    cart:       'M3 4h2l2.4 12.2a1 1 0 0 0 1 .8h8.7a1 1 0 0 0 1-.8L21 7H6',
    checkout:   'M9 11l3 3L22 4|M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11',
    thankyou:   'M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z',
    myaccount:  'M12 8a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z|M4 21a8 8 0 0 1 16 0',
    header:     'M4 6h16M4 12h10M4 18h7',
    offer:      'M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z',
    landing:    'M2 3h20v18H2Z|M2 9h20M9 21V9',
  };
  const SecIcon = ({ cat }) => {
    const paths = (CAT_ICONS[cat] || 'M12 2 2 7l10 5 10-5-10-5Z|M2 17l10 5 10-5|M2 12l10 5 10-5').split('|');
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        {paths.map((d, i) => <path key={i} d={d} />)}
      </svg>
    );
  };

  // Configuration for known categories
  const categoryConfig = storebuild.categories || {};

  const getCategoryInfo = (cat) => {
    const slug = cat.toLowerCase();
    if (categoryConfig[slug]) {
        return categoryConfig[slug];
    }
    // Formatter for unknown categories
    const label = slug.charAt(0).toUpperCase() + slug.slice(1).replace(/-/g, ' ');
    return {
        label: label,
        title: `${label} Widgets`,
        order: 100 // Default order for new categories
    };
  };

  // Get unique categories and sort them
  const categories = useMemo(() => {
    const cats = new Set();
    Object.values(addons).forEach(addon => {
        if (addon.category) {
            cats.add(addon.category.toLowerCase());
        }
    });

    return Array.from(cats).sort((a, b) => {
        const orderA = getCategoryInfo(a).order;
        const orderB = getCategoryInfo(b).order;
        // if orders are equal (new categories), sort alphabetically
        if (orderA === orderB) {
            return a.localeCompare(b);
        }
        return orderA - orderB;
    });
  }, [addons]);

  // Force active tab to be valid if possible, or fallback to first category.
  // Covers a stale tab restored from localStorage that no longer exists.
  useMemo(() => {
      if (categories.length > 0 && !categories.includes(activeTab)) {
          selectTab(categories[0]);
      }
  }, [categories, activeTab]);


  const activeWidgets = useMemo(() => {
    return Object.entries(addons).filter(([key, value]) => value?.category.toLowerCase() === activeTab);
  }, [addons, activeTab]);

  const visibleWidgets = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return activeWidgets;
    return activeWidgets.filter(([, value]) => (value.title || '').toLowerCase().includes(q));
  }, [activeWidgets, query]);

  const activeCategoryInfo = getCategoryInfo(activeTab);

  return (
    <div className="widget-tabs">
      {/* Tab Navigation */}
      <ul className="tab-nav">
        {categories.map((cat) => (
            <li
                key={cat}
                className={activeTab === cat ? 'active' : ''}
                onClick={() => selectTab(cat)}
            >
                <SecIcon cat={cat} />
                {getCategoryInfo(cat).label}
            </li>
        ))}
      </ul>

      {/* Render the Widgets based on the active tab */}
      <div className={"tab-content" + (view === 'list' ? ' strb-view-list' : '')}>
          <div className="strb-widget-row">
            <div className="strb-wsec-head">
              <div className="strb-wsec-ic"><SecIcon cat={activeTab} /></div>
              <div className="strb-wsec-meta">
                <h3>{activeCategoryInfo.title}</h3>
                <p>{`Manage and configure ${activeCategoryInfo.label.toLowerCase()} widgets.`}</p>
              </div>
              <div className="strb-wsec-tools">
                <label className="strb-wsearch">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7" /><path d="m21 21-4-4" /></svg>
                  <input
                    type="text"
                    placeholder="Search widgets…"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                  />
                </label>
                <div className="strb-vtog">
                  <button type="button" className={view === 'grid' ? 'active' : ''} aria-label="Grid view" onClick={() => setView('grid')}>
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1" /><rect x="14" y="3" width="7" height="7" rx="1" /><rect x="3" y="14" width="7" height="7" rx="1" /><rect x="14" y="14" width="7" height="7" rx="1" /></svg>
                  </button>
                  <button type="button" className={view === 'list' ? 'active' : ''} aria-label="List view" onClick={() => setView('list')}>
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01" /></svg>
                  </button>
                </div>
              </div>
            </div>
            <div className="strb-row">
              {visibleWidgets.map((val, key) => (
                <div className="strb-col-xxl-4 strb-col-lg-4 strb-col-md-6" key={key}>
                  <Widget
                    widget={2}
                    id={val[0]}
                    title={val[1].title}
                    isPro={val[1].is_pro}
                    onChange={handleChange}
                    defaultValue={val[1].is_active}
                    active={isProActive}
                  />
                </div>
              ))}
              {visibleWidgets.length === 0 && (
                <p style={{ padding: '30px 4px', color: '#8b8aa7' }}>No widgets match your search.</p>
              )}
            </div>
          </div>
      </div>
    </div>
  );
};

export default WidgetTabs;
