import * as React from 'react';
import { useState } from 'react';
import Editor from '@monaco-editor/react';

/**
 * Inline prompt editor: name + priority + Monaco for content.
 * Used by ProjectPrompts, AgentDetail (direct prompts tab), and
 * PersonalityDetail (binding-attached prompts).
 *
 * The component is intentionally dumb — it owns no I/O. The parent does the
 * POST/PUT and decides whether to show this in "create" or "edit" mode.
 */
export interface PromptDraft {
  name: string;
  priority: number;
  content: string;
}

export interface PromptEditorProps {
  initial?: Partial<PromptDraft>;
  /** Lock the name field — used when editing existing prompts (name is the unique key). */
  nameLocked?: boolean;
  submitLabel: string;
  onSubmit: (draft: PromptDraft) => Promise<void> | void;
  onCancel?: () => void;
  busy?: boolean;
}

export function PromptEditor(props: PromptEditorProps): React.JSX.Element {
  const [name, setName] = useState(props.initial?.name ?? '');
  const [priority, setPriority] = useState(props.initial?.priority ?? 5);
  const [content, setContent] = useState(props.initial?.content ?? '');
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent): Promise<void> {
    e.preventDefault();
    setError(null);
    if (!/^[a-z0-9-]+$/.test(name)) {
      setError('Name must be lowercase alphanumeric with hyphens (e.g., "tone-rules").');
      return;
    }
    if (content.trim().length === 0) {
      setError('Content is required.');
      return;
    }
    try {
      await props.onSubmit({ name, priority, content });
    } catch (err) {
      setError((err as Error).message);
    }
  }

  return (
    <form onSubmit={handleSubmit} style={styles.form}>
      <div style={styles.row}>
        <label style={styles.label}>
          Name
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            disabled={props.nameLocked === true}
            placeholder="lowercase-with-hyphens"
            style={styles.input}
          />
        </label>
        <label style={styles.label}>
          Priority (1-10)
          <input
            type="number"
            min={1}
            max={10}
            value={priority}
            onChange={(e) => setPriority(Number(e.target.value))}
            style={{ ...styles.input, width: 80 }}
          />
        </label>
      </div>
      <div style={styles.editorShell}>
        <Editor
          height="320px"
          theme="vs-dark"
          defaultLanguage="markdown"
          value={content}
          onChange={(v) => setContent(v ?? '')}
          options={{
            minimap: { enabled: false },
            wordWrap: 'on',
            fontSize: 13,
            automaticLayout: true,
          }}
        />
      </div>
      {error !== null && <div style={styles.error}>{error}</div>}
      <div style={styles.actions}>
        <button type="submit" disabled={props.busy === true} style={styles.primary}>
          {props.busy === true ? 'Saving…' : props.submitLabel}
        </button>
        {props.onCancel !== undefined && (
          <button type="button" onClick={props.onCancel} style={styles.secondary}>
            Cancel
          </button>
        )}
      </div>
    </form>
  );
}

const styles: Record<string, React.CSSProperties> = {
  form: { display: 'flex', flexDirection: 'column', gap: 12 },
  row: { display: 'flex', gap: 16, alignItems: 'flex-end' },
  label: {
    display: 'flex',
    flexDirection: 'column',
    gap: 4,
    fontSize: 12,
    color: '#7d8590',
    flex: 1,
  },
  input: {
    background: '#0d1117',
    color: '#c9d1d9',
    border: '1px solid #30363d',
    borderRadius: 4,
    padding: '6px 10px',
    fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
  },
  editorShell: { border: '1px solid #30363d', borderRadius: 4, overflow: 'hidden' },
  error: {
    background: '#2d1416',
    color: '#ff7b72',
    border: '1px solid #f85149',
    padding: '8px 12px',
    borderRadius: 4,
    fontSize: 13,
  },
  actions: { display: 'flex', gap: 8 },
  primary: {
    background: '#238636',
    color: '#fff',
    border: 'none',
    borderRadius: 4,
    padding: '8px 16px',
    cursor: 'pointer',
    fontWeight: 600,
  },
  secondary: {
    background: 'transparent',
    color: '#c9d1d9',
    border: '1px solid #30363d',
    borderRadius: 4,
    padding: '8px 16px',
    cursor: 'pointer',
  },
};
