import { useState } from 'react';
import { runCommunityRepoCommand } from '@/lib/tauri-bridge';
import { useActiveWorkspace, useWorkbenchStore } from '@/features/workspace/WorkspaceStore';

type RepoAction = 'list' | 'status' | 'push' | 'pull';

function plainTerminalOutput(value: string): string {
  return value.replace(/\u001b\[[0-9;]*m/g, '').trim();
}

export function CommunityRepoPanel() {
  const workspace = useActiveWorkspace();
  const cliPath = useWorkbenchStore((state) => state.settings.vigthoriaCliPath);
  const auth = useWorkbenchStore((state) => state.auth);
  const [repositoryName, setRepositoryName] = useState('');
  const [visibility, setVisibility] = useState<'private' | 'restricted' | 'public'>('private');
  const [running, setRunning] = useState<RepoAction | null>(null);
  const [output, setOutput] = useState('Choose an operation to inspect or synchronize this workspace with Vigthoria Community.');

  const run = async (action: RepoAction) => {
    if (!workspace) return;
    if (!auth.authenticated) {
      setOutput('A valid Vigthoria login is required for Community repository operations.');
      return;
    }
    if (action === 'pull' && !repositoryName.trim()) {
      setOutput('Enter a Community repository name before pulling.');
      return;
    }
    if (action === 'push' && !window.confirm(
      `Push “${workspace.name}” to Vigthoria Community as ${visibility}?\n\nThis uploads readable project files from ${workspace.rootPath}.`,
    )) return;

    setRunning(action);
    setOutput(`${action === 'push' ? 'Uploading' : 'Running'} Community repository ${action}…`);
    try {
      const result = await runCommunityRepoCommand(
        action,
        workspace.rootPath,
        repositoryName.trim() || undefined,
        action === 'push' ? visibility : undefined,
        cliPath,
      );
      setOutput(plainTerminalOutput(result) || `${action} completed.`);
    } catch (error) {
      setOutput(plainTerminalOutput(error instanceof Error ? error.message : String(error)));
    } finally {
      setRunning(null);
    }
  };

  if (!workspace) {
    return <div className="services-panel__body"><p className="services-panel__error">Select a workspace first.</p></div>;
  }

  return (
    <div className="services-panel__body">
      <p className="services-panel__intro">
        Native controls for user repositories stored in Vigthoria Community. Market is not used as the repository backend.
      </p>
      <label className="services-panel__field">
        <span>Repository name (optional for push; required for pull)</span>
        <input value={repositoryName} onChange={(event) => setRepositoryName(event.target.value)} placeholder={workspace.name} />
      </label>
      <label className="services-panel__field">
        <span>Push visibility</span>
        <select value={visibility} onChange={(event) => setVisibility(event.target.value as typeof visibility)}>
          <option value="private">Private</option>
          <option value="restricted">Restricted</option>
          <option value="public">Public</option>
        </select>
      </label>
      <div className="services-panel__actions services-panel__actions--wrap">
        <button type="button" disabled={running !== null} onClick={() => void run('list')}>List repositories</button>
        <button type="button" disabled={running !== null} onClick={() => void run('status')}>Workspace status</button>
        <button type="button" disabled={running !== null} onClick={() => void run('pull')}>Pull</button>
        <button type="button" className="is-primary" disabled={running !== null} onClick={() => void run('push')}>
          {running === 'push' ? 'Pushing…' : 'Push to Community'}
        </button>
      </div>
      <pre className="services-panel__terminal">{output}</pre>
    </div>
  );
}

