import React, { useCallback } from 'react';
import { Box, FormHelperText, Tooltip, IconButton } from '@mui/material';
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-github";
import "ace-builds/src-noconflict/theme-tomorrow_night";
import { ContentCopy } from '@mui/icons-material';
import useDarkMode from 'src/hooks/useDarkTheme';

import { aceTheme } from '../../../../utils';
import { handleCopy } from '../../../../../../utils';
import { useStyles } from '../../../../components/ShowRenderedJson';

interface DataFormProps {
  onChange: (value: string) => void;
  errors: Record<string, string>;
  value?: any;
}
interface DataValueViewProps {
  value: any;
}

const DataForm: React.FC<DataFormProps> = ({ 
  onChange, 
  errors, 
  value 
}) => {
  const isDarkMode = useDarkMode();
  const theme = aceTheme(isDarkMode);
  const { classes } = useStyles();
  
  // Convert object to string if needed
  const displayValue = (value !== null && typeof value !== 'string') 
    ? JSON.stringify(value, null, 2)
    : (value || '');

  const handleCopyClick = useCallback(() => {
    handleCopy(displayValue);
  }, [displayValue]);

  const handleEditorLoad = useCallback(() => {
    onChange(displayValue);
  }, [onChange, displayValue]);

  return (
    <Box className={classes.editorContainer} sx={{ mt: 2 }}>
      <AceEditor
        mode="json"
        theme={theme}
        value={value}
        onChange={onChange}
        onLoad={handleEditorLoad}
        value={displayValue}
        tabSize={2}
        style={{
            width: '100%'
        }}
        setOptions={{
            maxLines: 16,
            minLines: 16,
            useWorker: false
        }}
        className={classes.editor}
      />
      <Tooltip title="Copy to clipboard" placement="left">
        <IconButton
          className={classes.copyButton}
          onClick={handleCopyClick}
          size="small"
          disabled={!displayValue}
        >
          <ContentCopy fontSize="small" />
        </IconButton>
      </Tooltip>
      {errors?.item_value && (
        <FormHelperText error>
          {errors.item_value}
        </FormHelperText>
      )}
    </Box>
  );
};

export const ValueView: React.FC<DataValueViewProps> = ({ value }) => {
  const { classes } = useStyles();
  const isDarkMode = useDarkMode();
  const theme = aceTheme(isDarkMode);
  
  // Convert object to string if needed
  const displayValue = (value !== null && typeof value !== 'string') 
    ? JSON.stringify(value, null, 2)
    : (value || '');
    
  return (
    <AceEditor
      mode="json"
      theme={theme}
      readOnly
      value={displayValue}
      tabSize={2}
      style={{
        width: '600px'
      }}
      setOptions={{
        maxLines: 8,
        minLines: 8,
        useWorker: false
      }}
      className={classes.editor}
    />
  );
};

export default DataForm;
