import {
  type CompletionContext,
  type CompletionResult,
  snippetCompletion,
} from '@codemirror/autocomplete';

const commandCompletions = [
  snippetCompletion('\\textbf{${text}}', { label: '\\textbf', detail: 'Bold text', type: 'keyword' }),
  snippetCompletion('\\textit{${text}}', { label: '\\textit', detail: 'Italic text', type: 'keyword' }),
  snippetCompletion('\\emph{${text}}', { label: '\\emph', detail: 'Emphasis', type: 'keyword' }),
  snippetCompletion('\\section{${title}}', { label: '\\section', detail: 'Section heading', type: 'keyword' }),
  snippetCompletion('\\subsection{${title}}', { label: '\\subsection', detail: 'Subsection heading', type: 'keyword' }),
  snippetCompletion('\\chapter{${title}}', { label: '\\chapter', detail: 'Chapter heading', type: 'keyword' }),
  snippetCompletion('\\cite{${key}}', { label: '\\cite', detail: 'Citation', type: 'keyword' }),
  snippetCompletion('\\ref{${label}}', { label: '\\ref', detail: 'Reference', type: 'keyword' }),
  snippetCompletion('\\label{${label}}', { label: '\\label', detail: 'Label', type: 'keyword' }),
  snippetCompletion('\\includegraphics[width=0.8\\linewidth]{${path}}', { label: '\\includegraphics', detail: 'Include image', type: 'keyword' }),
  snippetCompletion('\\usepackage{${package}}', { label: '\\usepackage', detail: 'Import package', type: 'keyword' }),
  snippetCompletion('\\frac{${numerator}}{${denominator}}', { label: '\\frac', detail: 'Fraction', type: 'keyword' }),
  snippetCompletion('\\sqrt{${value}}', { label: '\\sqrt', detail: 'Square root', type: 'keyword' }),
  ...['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'theta', 'lambda', 'mu', 'pi', 'sigma', 'phi', 'omega', 'infty', 'partial', 'nabla', 'cdot', 'times', 'leq', 'geq', 'neq', 'approx'].map((name) => ({
    label: `\\${name}`,
    type: 'keyword' as const,
  })),
];

const environments = [
  'document',
  'figure',
  'figure*',
  'table',
  'tabular',
  'equation',
  'equation*',
  'align',
  'align*',
  'gather',
  'gather*',
  'itemize',
  'enumerate',
  'description',
  'abstract',
  'center',
  'minipage',
  'frame',
  'verbatim',
  'quote',
  'theorem',
  'proof',
  'lemma',
  'definition',
  'matrix',
  'bmatrix',
  'pmatrix',
  'cases',
  'split',
  'multline',
];

export function latexCompletionSource(context: CompletionContext): CompletionResult | null {
  const environmentMatch = context.matchBefore(/\\(begin|end)\{[a-zA-Z*]*/);
  if (environmentMatch) {
    const braceIndex = environmentMatch.text.indexOf('{');
    return {
      from: environmentMatch.from + braceIndex + 1,
      options: environments.map((environment) => ({
        label: environment,
        type: 'type',
      })),
      validFor: /^[a-zA-Z*]*$/,
    };
  }

  const commandMatch = context.matchBefore(/\\[a-zA-Z]*/);
  if (!commandMatch) return null;
  return {
    from: commandMatch.from,
    options: commandCompletions,
    validFor: /^\\[a-zA-Z]*$/,
  };
}

