import { useEffect, useState } from 'react';
import { WORKSPACE_PRESETS } from '@/lib/presets';
import { VigthoriaLogo } from '@/components/VigthoriaLogo';
import { isUsableProjectRoot } from '@/lib/workspace-path';
import { pickDirectory } from '@/lib/tauri-bridge';
import type { V4ProviderId, WorkspacePresetId } from '@/types/workbench';
import { FileTree } from '@/features/files/FileTree';
import { useActiveWorkspace, useWorkbenchStore } from '@/features/workspace/WorkspaceStore';

export function Sidebar() {
  const pathPlaceholder = navigator.userAgent.includes('Windows')
    ? 'C:\\Projects\\my-game'
    : navigator.userAgent.includes('Mac')
      ? '/Users/you/Projects/my-game'
      : '/home/you/Projects/my-game';
  const workspaces = useWorkbenchStore((s) => s.workspaces);
  const activeWorkspaceId = useWorkbenchStore((s) => s.activeWorkspaceId);
  const selectWorkspace = useWorkbenchStore((s) => s.selectWorkspace);
  const deleteWorkspace = useWorkbenchStore((s) => s.deleteWorkspace);
  const addWorkspace = useWorkbenchStore((s) => s.addWorkspace);
  const setWorkspaceRootPath = useWorkbenchStore((s) => s.setWorkspaceRootPath);
  const vigthoriaCliPath = useWorkbenchStore((s) => s.vigthoriaCliPath);
  const auth = useWorkbenchStore((s) => s.auth);
  const refreshAuth = useWorkbenchStore((s) => s.refreshAuth);
  const startLogin = useWorkbenchStore((s) => s.startLogin);
  const setSettingsOpen = useWorkbenchStore((s) => s.setSettingsOpen);

  const [name, setName] = useState('My Project');
  const [rootPath, setRootPath] = useState('');
  const [presetId, setPresetId] = useState<WorkspacePresetId>('agentDev');
  const [v4Provider, setV4Provider] = useState<V4ProviderId>('cloud');
  const [pathError, setPathError] = useState('');

  const active = useActiveWorkspace();
  const [projectPath, setProjectPath] = useState('');

  useEffect(() => {
    if (active?.rootPath) {
      setProjectPath(active.rootPath);
    }
  }, [active?.id, active?.rootPath]);

  const browseForFolder = async () => {
    const picked = await pickDirectory(rootPath || undefined);
    if (picked) {
      setRootPath(picked);
      if (name === 'My Project') {
        const parts = picked.replace(/\\/g, '/').split('/').filter(Boolean);
        setName(parts[parts.length - 1] || 'My Project');
      }
    }
  };

  const browseProjectFolder = async () => {
    const picked = await pickDirectory(projectPath || rootPath || undefined);
    if (picked) setProjectPath(picked);
  };

  const applyProjectFolder = async () => {
    const trimmed = projectPath.trim();
    if (!(await isUsableProjectRoot(trimmed))) {
      setPathError(`Choose an existing project folder (not the Workbench install folder): ${trimmed || '(empty)'}`);
      return;
    }
    setPathError('');
    await setWorkspaceRootPath(trimmed);
  };

  return (
    <aside className="sidebar">
      <div className="sidebar__brand">
        <VigthoriaLogo size={36} className="sidebar__logo" />
        <div>
          <div className="sidebar__title">Vigthoria</div>
          <div className="sidebar__subtitle">Workbench</div>
        </div>
        <button type="button" className="sidebar__settings" onClick={() => setSettingsOpen(true)} title="Settings">
          ⚙
        </button>
      </div>

      <section className="sidebar__section">
        <div className="sidebar__section-title">Workspaces</div>
        {workspaces.length === 0 ? (
          <p className="sidebar__empty">No workspaces yet. Create one below.</p>
        ) : (
          <ul className="sidebar__list">
            {workspaces.map((workspace) => (
              <li key={workspace.id} className="sidebar__workspace-row">
                <button
                  type="button"
                  className={`sidebar__item ${workspace.id === activeWorkspaceId ? 'is-active' : ''}`}
                  onClick={() => void selectWorkspace(workspace.id)}
                >
                  <span className="sidebar__item-name">{workspace.name}</span>
                  <span className="sidebar__item-path">{workspace.rootPath}</span>
                  <span className="sidebar__item-preset">{workspace.preset}</span>
                </button>
                <button
                  type="button"
                  className="sidebar__workspace-delete"
                  title={`Delete workspace “${workspace.name}”`}
                  aria-label={`Delete workspace ${workspace.name}`}
                  onClick={() => {
                    if (window.confirm(`Delete workspace “${workspace.name}” from Workbench?\n\nProject files will not be deleted.`)) {
                      void deleteWorkspace(workspace.id).catch((error: unknown) => {
                        window.alert(error instanceof Error ? error.message : String(error));
                      });
                    }
                  }}
                >
                  ×
                </button>
              </li>
            ))}
          </ul>
        )}
      </section>

      {active && (
        <section className="sidebar__section sidebar__section--highlight">
          <div className="sidebar__section-title">Project folder</div>
          <p className="sidebar__hint">All terminals run in this directory (<code>npm run dev</code>, <code>vigthoria agent</code>).</p>
          <label className="sidebar__field">
            <span>Path for “{active.name}”</span>
            <div className="sidebar__path-row">
              <input value={projectPath} onChange={(e) => setProjectPath(e.target.value)} placeholder={pathPlaceholder} />
              <button type="button" onClick={() => void browseProjectFolder()}>Browse</button>
            </div>
          </label>
          <button type="button" className="sidebar__cta sidebar__cta--secondary" onClick={() => void applyProjectFolder()}>
            Apply &amp; restart terminals
          </button>
        </section>
      )}

      <section className="sidebar__section">
        <div className="sidebar__section-title">New workspace</div>
        <label className="sidebar__field">
          <span>Preset</span>
          <select value={presetId} onChange={(e) => setPresetId(e.target.value as WorkspacePresetId)}>
            {WORKSPACE_PRESETS.map((preset) => (
              <option key={preset.id} value={preset.id}>{preset.name}</option>
            ))}
          </select>
        </label>
        <p className="sidebar__hint">{WORKSPACE_PRESETS.find((p) => p.id === presetId)?.description}</p>
        {presetId === 'v4Operating' && (
          <label className="sidebar__field">
            <span>V4 Provider</span>
            <select value={v4Provider} onChange={(e) => setV4Provider(e.target.value as V4ProviderId)}>
              <option value="cloud">Vigthoria Cloud (Gateway + Session Wallet Token)</option>
              <option value="v3_local">Vigthoria V3 Local (private infrastructure network only)</option>
              <option value="byok">Bring Your Own Key (Custom Provider)</option>
            </select>
            {v4Provider === 'byok' && (
              <p className="sidebar__hint">
                Uses the API key configured in Settings &rarr; API Management. Configure it there before launching.
              </p>
            )}
            {v4Provider === 'v3_local' && (
              <p className="sidebar__hint">
                Private-network mode connects to Vigthoria infrastructure addresses that are not reachable from normal external machines. Use Cloud unless this workstation is on the Vigthoria private network.
              </p>
            )}
          </label>
        )}
        <label className="sidebar__field">
          <span>Name</span>
          <input value={name} onChange={(e) => setName(e.target.value)} />
        </label>
        <label className="sidebar__field">
          <span>Root path</span>
          <div className="sidebar__path-row">
            <input value={rootPath} onChange={(e) => setRootPath(e.target.value)} placeholder={pathPlaceholder} />
            <button type="button" onClick={() => void browseForFolder()}>Browse</button>
          </div>
        </label>
        {pathError && <p className="sidebar__error">{pathError}</p>}
        <button
          type="button"
          className="sidebar__cta"
          onClick={() => {
            void (async () => {
              const trimmed = rootPath.trim();
              if (!(await isUsableProjectRoot(trimmed))) {
                setPathError('Browse to your game/project folder (must exist and contain your code — not the Workbench install folder).');
                return;
              }
              setPathError('');
              await addWorkspace(
                name.trim() || 'Workspace',
                trimmed,
                presetId,
                presetId === 'v4Operating' ? { v4Provider } : undefined,
              );
              setRootPath('');
            })();
          }}
        >
          Create workspace
        </button>
      </section>

      <FileTree />

      <section className="sidebar__meta">
        <div className="sidebar__meta-row">
          <span>Account</span>
          <button
            type="button"
            className={`sidebar__auth ${auth.authenticated ? 'ok' : 'warn'}`}
            onClick={() => {
              if (auth.authenticated || auth.hasToken) {
                void refreshAuth(true);
              } else {
                void startLogin().then(() => refreshAuth(true)).catch(() => refreshAuth(true));
              }
            }}
            title={auth.message}
          >
            {auth.authenticated ? (auth.email || 'logged in') : 'login'}
          </button>
        </div>
        <div className="sidebar__meta-row">
          <span>CLI</span>
          <span className={vigthoriaCliPath ? 'ok' : 'warn'}>
            {vigthoriaCliPath ? 'detected' : 'not found'}
          </span>
        </div>
        {active && (
          <div className="sidebar__meta-row">
            <span>Main</span>
            <span className="sidebar__meta-truncate">{active.rootPath}</span>
          </div>
        )}
      </section>
    </aside>
  );
}
