import { CodeHighlight } from '@mantine/code-highlight';
import * as prettier from 'prettier/standalone';
import { useEffect, useState } from 'react';
import * as parserTypeScript from 'prettier/plugins/typescript';
import * as parserEsTree from 'prettier/plugins/estree';

export function CodeComponent({ code, language = 'tsx', format = false }: any) {
  const [formattedCode, setFormattedCode] = useState(code);

  useEffect(() => {
    (async () => {
      if (format) {
        try {
          const output = await prettier.format(code, {
            parser: language === 'json' ? 'json' : 'typescript',
            plugins: [parserTypeScript, parserEsTree],
          });

          setFormattedCode(output);
        } catch (e) {
          console.warn('Failed to format code:', e);
        }
      }
    })();
  }, []);

  if (!formattedCode) return;

  return <CodeHighlight code={formattedCode} language={language} withCopyButton={false} />;
}
