import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapSwitch from '@capillarytech/cap-ui-library/CapSwitch';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import messages from './messages';

const CustomValuesEditor = ({
  isExtractingTags,
  isUpdatePreviewDisabled,
  showJSON,
  setShowJSON,
  customValues,
  handleJSONTextChange,
  extractedTags,
  requiredTags,
  optionalTags,
  handleCustomValueChange,
  handleDiscardCustomValues,
  handleUpdatePreview,
  isUpdatingPreview,
  formatMessage,
}) => {
  if (isExtractingTags) {
    return (
      <CapRow type="flex" vertical noWrap align="middle" justify="center" className="loading-container">
        <CapSpin size="large" />
        <CapRow useLegacy className="loading-text">
          <FormattedMessage {...messages.extractingTags} />
        </CapRow>
      </CapRow>
    );
  }

  return (
    <CapRow className="custom-values-editor">
      {isUpdatePreviewDisabled && (
        <CapLabel type="label16" className="values-missing-message">
          <FormattedMessage {...messages.valuesMissing} />
        </CapLabel>
      )}
      <CapRow className="editor-header">
        <CapRow className="json-toggle">
          <span className="toggle-label">
            <FormattedMessage {...messages.showJSON} />
          </span>
          <CapSwitch
            checked={showJSON}
            onChange={setShowJSON}
            size="small"
          />
        </CapRow>
      </CapRow>
      {showJSON ? (
        <CapRow className="json-editor">
          <CapRow className="json-editor-container">
            <CapRow className="line-numbers">
              {JSON.stringify(customValues, null, 2).split('\n').map((_, index) => (
                <CapRow key={`line-${index + 1}`} className="line-number">
                  {index + 1}
                </CapRow>
              ))}
            </CapRow>
            <textarea
              className="json-textarea"
              value={JSON.stringify(customValues, null, 2)}
              onChange={(e) => handleJSONTextChange(e.target.value)}
              placeholder={formatMessage(messages.enterValue)}
              rows={Math.max(10, JSON.stringify(customValues, null, 2).split('\n').length)}
              spellCheck={false}
            />
          </CapRow>
        </CapRow>
      ) : (
        <>
          {extractedTags?.length > 0 && (
            <CapRow className="values-table">
              <CapRow type="flex" className="table-header">
                <CapLabel type="label31" className="header-cell">
                  <FormattedMessage {...messages.personalizationTags} />
                </CapLabel>
                <CapLabel type="label31" className="header-cell">
                  <FormattedMessage {...messages.customValues} />
                </CapLabel>
              </CapRow>
              {requiredTags.map((tag) => (
                <CapRow key={tag.fullPath} className="value-row">
                  <CapRow className="tag-name">
                    {tag.fullPath}
                    <span className="required-tag-indicator">*</span>
                  </CapRow>
                  <CapRow className="tag-input">
                    <CapInput
                      type="text"
                      isRequired
                      className="tag-input-field"
                      value={customValues[tag.fullPath] || ''}
                      onChange={(e) => handleCustomValueChange(tag.fullPath, e.target.value)}
                      placeholder={formatMessage(messages.enterValue)}
                      size="small"
                    />
                  </CapRow>
                </CapRow>
              ))}
              {optionalTags.map((tag) => (
                <CapRow key={tag.fullPath} className="value-row">
                  <CapRow className="tag-name">{tag.fullPath}</CapRow>
                  <CapRow className="tag-input">
                    <CapInput
                      type="text"
                      className="tag-input-field"
                      value={customValues[tag.fullPath] || ''}
                      onChange={(e) => handleCustomValueChange(tag.fullPath, e.target.value)}
                      placeholder={formatMessage(messages.enterValue)}
                      size="small"
                    />
                  </CapRow>
                </CapRow>
              ))}
            </CapRow>
          )}
        </>
      )}
      <div className="editor-actions">
        <CapButton
          className="discard-button"
          type="link"
          size="small"
          onClick={handleDiscardCustomValues}
          icon="close"
        >
          <FormattedMessage {...messages.discardCustomValues} />
        </CapButton>
        <CapButton
          type="primary"
          size="small"
          onClick={handleUpdatePreview}
          loading={isUpdatingPreview}
          disabled={isUpdatePreviewDisabled}
        >
          <FormattedMessage {...messages.updatePreview} />
        </CapButton>
      </div>
    </CapRow>
  );
};

CustomValuesEditor.propTypes = {
  isExtractingTags: PropTypes.bool.isRequired,
  isUpdatePreviewDisabled: PropTypes.bool.isRequired,
  showJSON: PropTypes.bool.isRequired,
  setShowJSON: PropTypes.func.isRequired,
  customValues: PropTypes.object.isRequired,
  handleJSONTextChange: PropTypes.func.isRequired,
  extractedTags: PropTypes.array.isRequired,
  requiredTags: PropTypes.array.isRequired,
  optionalTags: PropTypes.array.isRequired,
  handleCustomValueChange: PropTypes.func.isRequired,
  handleDiscardCustomValues: PropTypes.func.isRequired,
  handleUpdatePreview: PropTypes.func.isRequired,
  isUpdatingPreview: PropTypes.bool.isRequired,
  formatMessage: PropTypes.func.isRequired,
};

export default CustomValuesEditor;
