import React, { useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import messages from '../messages';
import { isValidHttpUrl } from '../utils/urlValidation';
import { WEBPUSH_BUTTON_TYPES, BUTTON_TEXT_MAX_LENGTH } from '../../constants';

const ButtonForm = ({
  buttonType, // 'primary' or 'secondary'
  formatMessage,
  onSave,
  onCancel,
  initialData,
  isEditMode,
}) => {
  const [buttonText, setButtonText] = useState(initialData?.text || '');
  const [buttonUrl, setButtonUrl] = useState(initialData?.url || '');
  const [buttonTextError, setButtonTextError] = useState('');
  const [buttonUrlError, setButtonUrlError] = useState('');

  const validateButtonText = useCallback((value) => {
    if (!value || value.trim() === '') {
      return formatMessage(messages.buttonTextRequired);
    }
    return '';
  }, [formatMessage]);

  const validateButtonUrl = useCallback((value) => {
    if (!value || value.trim() === '') {
      return formatMessage(messages.buttonUrlRequired);
    }

    if (!isValidHttpUrl(value)) {
      return formatMessage(messages.buttonUrlInvalid);
    }

    return '';
  }, [formatMessage]);

  const handleButtonTextChange = useCallback((e) => {
    const { value } = e.target;
    setButtonText(value);
    const nextError = validateButtonText(value);
    setButtonTextError((prev) => (prev === nextError ? prev : nextError));
  }, [validateButtonText]);

  const handleButtonUrlChange = useCallback((e) => {
    const { value } = e.target;
    setButtonUrl(value);
    const nextError = validateButtonUrl(value);
    setButtonUrlError((prev) => (prev === nextError ? prev : nextError));
  }, [validateButtonUrl]);

  const handleSave = useCallback(() => {
    const textError = validateButtonText(buttonText);
    const urlError = validateButtonUrl(buttonUrl);

    if (textError || urlError) {
      setButtonTextError(textError);
      setButtonUrlError(urlError);
      return;
    }

    onSave({
      text: buttonText.trim(),
      url: buttonUrl.trim(),
      type: buttonType,
    });
  }, [buttonText, buttonUrl, buttonType, onSave, validateButtonText, validateButtonUrl]);

  const handleCancel = useCallback(() => {
    onCancel();
  }, [onCancel]);

  const isSaveDisabled = !buttonText.trim() || !buttonUrl.trim() || buttonTextError || buttonUrlError;

  const renderCharacterCountSuffix = () => {
    const currentLength = buttonText.length;
    const maxLength = BUTTON_TEXT_MAX_LENGTH;

    return (
      <span className="button-character-count-suffix">
        {`${currentLength}/${maxLength}`}
      </span>
    );
  };

  const handleKeyDown = useCallback((e) => {
    if (e.key === 'Enter' && !isSaveDisabled) {
      e.preventDefault();
      handleSave();
    }
  }, [handleSave, isSaveDisabled]);

  return (
    <div className="webpush-button-form" onKeyDown={handleKeyDown}>
      <CapRow className="button-form-row">
        <CapHeading type="h4" className="button-form-heading">
          <FormattedMessage {...messages.buttonText} />
        </CapHeading>
        <div className="button-form-field">
          <CapInput
            id={`webpush-button-text-input-${buttonType}`}
            placeholder={formatMessage(messages.buttonTextPlaceholder)}
            value={buttonText}
            onChange={handleButtonTextChange}
            maxLength={BUTTON_TEXT_MAX_LENGTH}
            size="default"
            status={buttonTextError ? 'error' : ''}
            help={buttonTextError || ''}
            suffix={renderCharacterCountSuffix()}
          />
        </div>
      </CapRow>
      <CapRow className="button-form-row">
        <CapHeading type="h4" className="button-form-heading">
          <FormattedMessage {...messages.buttonUrlLabel} />
        </CapHeading>
        <CapInput
          id={`webpush-button-url-input-${buttonType}`}
          placeholder={formatMessage(messages.buttonUrlPlaceholder)}
          value={buttonUrl}
          onChange={handleButtonUrlChange}
          size="default"
          status={buttonUrlError ? 'error' : ''}
          help={buttonUrlError || ''}
        />
      </CapRow>
      <CapRow className="button-form-actions">
        <CapButton
          type="primary"
          onClick={handleSave}
          disabled={isSaveDisabled}
          className="button-form-save"
        >
          <FormattedMessage {...messages.saveButton} />
        </CapButton>
        <CapButton
          type="secondary"
          onClick={handleCancel}
          className="button-form-cancel"
        >
          <FormattedMessage {...(isEditMode ? messages.cancelButton : messages.deleteButton)} />
        </CapButton>
      </CapRow>
    </div>
  );
};

ButtonForm.propTypes = {
  buttonType: PropTypes.oneOf([WEBPUSH_BUTTON_TYPES.PRIMARY, WEBPUSH_BUTTON_TYPES.SECONDARY]).isRequired,
  formatMessage: PropTypes.func.isRequired,
  onSave: PropTypes.func.isRequired,
  onCancel: PropTypes.func.isRequired,
  initialData: PropTypes.shape({
    text: PropTypes.string,
    url: PropTypes.string,
  }),
  isEditMode: PropTypes.bool,
};

ButtonForm.defaultProps = {
  initialData: null,
  isEditMode: false,
};

export default ButtonForm;

