import { useEffect, useState, useMemo } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useAppStore, type GumpEntry, type ScriptGumpEntry } from '../../store/appStore';
import styles from './GumpBrowser.module.css';

interface Props {
  search: string;
}

type GumpTab = 'art' | 'scripts';

export default function GumpBrowser({ search }: Props) {
  const { setSelectedGump, setCenterMode, setSelectedScriptGump } = useAppStore();
  const [gumpTab, setGumpTab] = useState<GumpTab>('art');

  // Art gumps (from gumps.xml)
  const [artEntries, setArtEntries] = useState<GumpEntry[]>([]);
  const [artLoading, setArtLoading] = useState(true);
  const [artError, setArtError] = useState<string | null>(null);
  const [artActiveTag, setArtActiveTag] = useState<string>('all');

  // Script gumps (from script_gumps.xml)
  const [scriptEntries, setScriptEntries] = useState<ScriptGumpEntry[]>([]);
  const [scriptLoading, setScriptLoading] = useState(true);
  const [scriptError, setScriptError] = useState<string | null>(null);
  const [scriptActiveTag, setScriptActiveTag] = useState<string>('all');

  useEffect(() => {
    invoke<GumpEntry[]>('list_gumps')
      .then((data) => { setArtEntries(data); setArtLoading(false); })
      .catch((e) => { setArtError(String(e)); setArtLoading(false); });

    invoke<ScriptGumpEntry[]>('list_script_gumps')
      .then((data) => { setScriptEntries(data); setScriptLoading(false); })
      .catch((e) => { setScriptError(String(e)); setScriptLoading(false); });
  }, []);

  // ── Art tab ────────────────────────────────────────────────────────────────
  const artTopTags = useMemo(() => {
    const s = new Set<string>();
    for (const e of artEntries) for (const t of e.tags) s.add(t);
    return Array.from(s).sort();
  }, [artEntries]);

  const artFiltered = useMemo(() => {
    const q = search.toLowerCase();
    return artEntries.filter((e) => {
      const nameMatch = !q || e.name.toLowerCase().includes(q) || String(e.id).includes(q)
        || ('0x' + e.id.toString(16)).includes(q.replace('0x', ''));
      const tagMatch = artActiveTag === 'all' || e.tags.includes(artActiveTag);
      return nameMatch && tagMatch;
    });
  }, [artEntries, search, artActiveTag]);

  function selectArtGump(entry: GumpEntry) {
    setSelectedGump(entry);
    setCenterMode('gump_image');
  }

  // ── Script tab ─────────────────────────────────────────────────────────────
  const scriptTopTags = useMemo(() => {
    const s = new Set<string>();
    for (const e of scriptEntries) for (const t of e.tags) s.add(t);
    return Array.from(s).sort();
  }, [scriptEntries]);

  const scriptFiltered = useMemo(() => {
    const q = search.toLowerCase();
    return scriptEntries.filter((e) => {
      const nameMatch = !q || e.class_name.toLowerCase().includes(q)
        || e.file_path.toLowerCase().includes(q);
      const tagMatch = scriptActiveTag === 'all' || e.tags.includes(scriptActiveTag);
      return nameMatch && tagMatch;
    });
  }, [scriptEntries, search, scriptActiveTag]);

  function selectScriptGump(entry: ScriptGumpEntry) {
    setSelectedScriptGump(entry);
    setCenterMode('gump_render');
  }

  // ── Render ─────────────────────────────────────────────────────────────────
  return (
    <div className={styles.browser}>
      {/* Sub-tabs */}
      <div className={styles.subTabs}>
        <button
          className={`${styles.subTab} ${gumpTab === 'art' ? styles.subTabActive : ''}`}
          onClick={() => setGumpTab('art')}
        >
          Art ({artEntries.length})
        </button>
        <button
          className={`${styles.subTab} ${gumpTab === 'scripts' ? styles.subTabActive : ''}`}
          onClick={() => setGumpTab('scripts')}
        >
          Scripts ({scriptEntries.length})
        </button>
      </div>

      {/* Art tab */}
      {gumpTab === 'art' && (
        <>
          {artLoading && <div className={styles.status}>Loading art gumps…</div>}
          {artError && <div className={styles.error}>{artError}</div>}
          {!artLoading && !artError && (
            <>
              <div className={styles.tagBar}>
                <button
                  className={`${styles.tag} ${artActiveTag === 'all' ? styles.tagActive : ''}`}
                  onClick={() => setArtActiveTag('all')}
                >All</button>
                {artTopTags.map((t) => (
                  <button
                    key={t}
                    className={`${styles.tag} ${artActiveTag === t ? styles.tagActive : ''}`}
                    onClick={() => setArtActiveTag(t)}
                  >{t}</button>
                ))}
              </div>
              <div className={styles.count}>{artFiltered.length} gumps</div>
              <div className={styles.list}>
                {artFiltered.map((entry) => (
                  <button
                    key={entry.id}
                    className={styles.item}
                    onClick={() => selectArtGump(entry)}
                  >
                    <span className={styles.itemId}>
                      0x{entry.id.toString(16).toUpperCase().padStart(4, '0')}
                    </span>
                    <span className={styles.itemName}>{entry.name}</span>
                  </button>
                ))}
              </div>
            </>
          )}
        </>
      )}

      {/* Scripts tab */}
      {gumpTab === 'scripts' && (
        <>
          {scriptLoading && <div className={styles.status}>Loading script gumps…</div>}
          {scriptError && <div className={styles.error}>{scriptError}</div>}
          {!scriptLoading && !scriptError && (
            <>
              <div className={styles.tagBar}>
                <button
                  className={`${styles.tag} ${scriptActiveTag === 'all' ? styles.tagActive : ''}`}
                  onClick={() => setScriptActiveTag('all')}
                >All</button>
                {scriptTopTags.map((t) => (
                  <button
                    key={t}
                    className={`${styles.tag} ${scriptActiveTag === t ? styles.tagActive : ''}`}
                    onClick={() => setScriptActiveTag(t)}
                  >{t}</button>
                ))}
              </div>
              <div className={styles.count}>{scriptFiltered.length} classes</div>
              <div className={styles.list}>
                {scriptFiltered.map((entry) => (
                  <button
                    key={entry.class_name}
                    className={styles.item}
                    onClick={() => selectScriptGump(entry)}
                  >
                    <span className={styles.itemName}>{entry.class_name}</span>
                    <span className={styles.itemPath}>{entry.file_path}</span>
                  </button>
                ))}
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
}
