/**
 * @fileoverview React component for CodeViewer.jsx
 * 
 * @module pages.Playground.components.CodeViewer
 */

import React, { useState } from "react";
import { Copy, Check } from "lucide-react";
import CodeMirror from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import "./CodeViewer.css";

const CodeViewer = ({
  code,
  language = "javascript",
  title = "Código",
  theme = "light",
}) => {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      console.error("Erro ao copiar:", error);
    }
  };

  return (
    <div className={`code-viewer-container code-viewer-theme-${theme}`}>
      <button
        className={`code-viewer-copy-btn ${copied ? "copied" : ""}`}
        onClick={handleCopy}
        title="Copiar código"
      >
        {copied ? (
          <>
            <Check className="w-4 h-4" />
            <span>Copiado!</span>
          </>
        ) : (
          <>
            <Copy className="w-4 h-4" />
            <span>Copiar</span>
          </>
        )}
      </button>

      <div className="code-viewer-editor">
        <CodeMirror
          value={code || "// Nenhum código gerado ainda"}
          height="100%"
          theme={theme}
          extensions={[javascript()]}
          basicSetup={{
            lineNumbers: true,
            highlightActiveLineGutter: false,
            highlightActiveLine: false,
            foldGutter: false,
            dropCursor: false,
            allowMultipleSelections: false,
            indentOnInput: false,
            bracketMatching: true,
            closeBrackets: false,
            autocompletion: false,
            highlightSelectionMatches: false,
          }}
          editable={false}
          readOnly={true}
          className="h-full"
        />
      </div>
    </div>
  );
};

export default CodeViewer;
