import { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useAppStore } from '../../store/appStore';
import LeftPanel from './LeftPanel';
import CenterPanel from './CenterPanel';
import RightPanel from './RightPanel';
import ConfigScreen from '../config/ConfigScreen';
import styles from './AppShell.module.css';

export default function AppShell() {
  const { centerMode, setCenterMode, uoRoot, servuoScripts } = useAppStore();
  const [indexingAssets, setIndexingAssets] = useState(false);
  const [indexingScripts, setIndexingScripts] = useState(false);

  async function handleIndexAssets() {
    if (!uoRoot) return;
    setIndexingAssets(true);
    try {
      const count = await invoke<number>('index_assets', { uoRoot });
      alert(`Indexed ${count.toLocaleString()} tiles.`);
    } catch (e) {
      alert(`Asset index failed: ${e}`);
    } finally {
      setIndexingAssets(false);
    }
  }

  async function handleIndexScripts() {
    if (!servuoScripts) {
      alert('Set the ServUO Scripts path in Config first.');
      return;
    }
    setIndexingScripts(true);
    try {
      const count = await invoke<number>('index_scripts', { scriptsPath: servuoScripts });
      alert(`Indexed ${count.toLocaleString()} classes.`);
    } catch (e) {
      alert(`Script index failed: ${e}`);
    } finally {
      setIndexingScripts(false);
    }
  }

  return (
    <div className={styles.shell}>
      <header className={styles.header}>
        <span className={`${styles.title} font-cinzel`}>Artificer's Scrollwork</span>
        <div className={styles.headerActions}>
          <button
            className={styles.headerBtn}
            onClick={handleIndexAssets}
            disabled={indexingAssets}
          >
            {indexingAssets ? 'Indexing…' : '[Assets]'}
          </button>
          <button
            className={styles.headerBtn}
            onClick={handleIndexScripts}
            disabled={indexingScripts}
          >
            {indexingScripts ? 'Indexing…' : '[Scripts]'}
          </button>
          <button
            className={styles.headerBtn}
            onClick={() => setCenterMode('config')}
          >
            [Config]
          </button>
        </div>
      </header>

      {centerMode === 'config' ? (
        <ConfigScreen onDone={() => setCenterMode('empty')} />
      ) : (
        <div className={styles.panels}>
          <LeftPanel />
          <CenterPanel />
          <RightPanel />
        </div>
      )}
    </div>
  );
}
