import React, { useState } from "react";
import PropTypes from "prop-types";
import { Box, Button, Flex, Textarea, Typography } from "@strapi/design-system";

const AdvancedTab = ({ config, onChange }) => {
  const [text, setText] = useState(JSON.stringify(config, null, 2));
  const [error, setError] = useState(null);

  const handleApply = () => {
    try {
      const parsed = JSON.parse(text);
      if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
        throw new Error("Config must be a JSON object");
      }
      setError(null);
      onChange(parsed);
    } catch (parseError) {
      setError(parseError.message);
    }
  };

  return (
    <Flex direction="column" alignItems="stretch" gap={3}>
      <Typography variant="pi" textColor="neutral500">
        Raw CKEditor config (everything except plugins and toolbar). Full reference:
        ckeditor.com/docs/ckeditor5/latest/api/module_core_editor_editorconfig-EditorConfig.html
      </Typography>
      <Textarea
        name="advanced-config"
        value={text}
        onChange={(event) => setText(event.target.value)}
        spellCheck={false}
        style={{ minHeight: 420, fontFamily: "monospace", fontSize: 13 }}
      />
      {error && (
        <Typography variant="pi" textColor="danger600">
          {error}
        </Typography>
      )}
      <Box>
        <Button variant="secondary" onClick={handleApply}>
          Apply JSON
        </Button>
      </Box>
    </Flex>
  );
};

AdvancedTab.propTypes = {
  config: PropTypes.object.isRequired,
  onChange: PropTypes.func.isRequired,
};

export default AdvancedTab;
