import { useEffect, useState, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useAppStore } from '../../store/appStore';
import type { TileInfo } from '../../types/assets';
import styles from './StaticBrowser.module.css';

interface TileRow {
  id: number;
  name: string;
  flags: number;
  weight: number;
  quality: number;
  height: number;
  hue: number;
  anim_id: number;
}

const PAGE_SIZE = 100;

interface Props {
  search: string;
}

export default function StaticBrowser({ search }: Props) {
  const { setSelectedTile, setCenterMode } = useAppStore();
  const [tiles, setTiles] = useState<TileRow[]>([]);
  const [offset, setOffset] = useState(0);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);

  const loadTiles = useCallback(async (newOffset: number, q: string) => {
    setLoading(true);
    try {
      const rows = await invoke<TileRow[]>('list_static_tiles', {
        offset: newOffset,
        limit: PAGE_SIZE,
        search: q || null,
      });
      if (newOffset === 0) {
        setTiles(rows);
      } else {
        setTiles((prev) => [...prev, ...rows]);
      }
      setHasMore(rows.length === PAGE_SIZE);
    } catch {
      // Index not yet built — show empty state
      setTiles([]);
      setHasMore(false);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    setOffset(0);
    loadTiles(0, search);
  }, [search, loadTiles]);

  function selectTile(row: TileRow) {
    const tile: TileInfo = {
      id: row.id,
      name: row.name,
      flags: row.flags,
      weight: row.weight,
      quality: row.quality,
      height: row.height,
      hue: row.hue,
      animId: row.anim_id,
    };
    setSelectedTile(tile);
    setCenterMode('asset_static');
  }

  if (!loading && tiles.length === 0) {
    return (
      <div className={styles.empty}>
        No tiles indexed yet.
        <br />
        Click [Index] in the toolbar after setting up your paths.
      </div>
    );
  }

  return (
    <div className={styles.list}>
      {tiles.map((t) => (
        <button key={t.id} className={styles.row} onClick={() => selectTile(t)}>
          <span className={styles.id}>{t.id}</span>
          <span className={styles.name}>{t.name || '(unnamed)'}</span>
        </button>
      ))}
      {hasMore && (
        <button
          className={styles.loadMore}
          onClick={() => {
            const next = offset + PAGE_SIZE;
            setOffset(next);
            loadTiles(next, search);
          }}
          disabled={loading}
        >
          {loading ? 'Loading…' : 'Load more'}
        </button>
      )}
    </div>
  );
}
