/**
 * ValidationTabs Component
 *
 * Displays validation issues in a tabbed interface with 2 categories:
 * - Errors: Blocking issues (API errors, Rule Group #1, client-side Liquid errors)
 * - Warnings: Non-blocking issues
 */

import React, { useState, useMemo, useEffect } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl, intlShape } from 'react-intl';

// Cap UI Library
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapTooltip from '@capillarytech/cap-ui-library/CapTooltip';

// Messages
import messages from './messages';
import { BLOCKING_ERROR_RULE_IDS, VALIDATION_SEVERITY } from '../../constants';

// Styles
import './_validationTabs.scss';
import { StyledCapTab } from '../../../../v2Containers/MobilePushNew/style';
import { ISSUE_SOURCES } from '../../utils/validationConstants';

/**
 * Group issues into Errors (blocking) and Warnings (non-blocking)
 */
const groupByErrorsAndWarnings = (allIssues) => {
  const errors = [];
  const warnings = [];

  allIssues.forEach((issue) => {
    if (isBlockingError(issue)) {
      errors.push(issue);
    } else {
      warnings.push(issue);
    }
  });

  return { errors, warnings };
};

/**
 * Check if an issue is a blocking error (API error, Rule Group #1, or client-side Liquid validation errors)
 */
const isBlockingError = (issue) => {
  const { rule, source, severity } = issue || {};
  // API errors are blocking
  if (rule === 'liquid-api-validation' || rule === 'standard-api-validation') {
    return true;
  }
  // Client-side Liquid validation errors are blocking (genuine syntax errors)
  if (source === ISSUE_SOURCES.LIQUID && severity === VALIDATION_SEVERITY.ERROR) {
    return true;
  }
  // Rule Group #1 errors are blocking
  if (BLOCKING_ERROR_RULE_IDS.includes(rule)) {
    return true;
  }
  return false;
};

/**
 * ValidationTabContent - Renders the content for each tab
 */
const ValidationTabContent = ({
  issues,
  onErrorClick,
  onExpand,
}) => {
  if (!issues || issues.length === 0) {
    return null;
  }

  const handleNavigateClick = (issue, e) => {
    e.stopPropagation();
    // Expand panel when redirection is clicked so it does not stay stuck to footer
    if (onExpand) {
      onExpand();
    }
    if (onErrorClick) {
      // Always call onErrorClick to acknowledge the error (enables buttons)
      // If line number exists, navigate to it; otherwise just acknowledge and focus editor
      onErrorClick({
        line: issue.line || 1, // Default to line 1 if no line number (for API errors)
        column: issue.column || 1,
        message: issue.message,
        severity: issue.severity,
      });
    }
  };

  return (
    <div className="validation-tabs__content">
      {issues.map((issue, index) => {
        const {
          message, line, column,
        } = issue;
        const key = `${message}-${line}-${column}-${index}`;
        const isBlocking = isBlockingError(issue);
        const displaySeverity = isBlocking ? 'error' : 'warning';

        return (
          <div
            key={key}
            className={`validation-tabs__item validation-tabs__item--${displaySeverity}`}
          >
            <div className="validation-tabs__item-content">
              <span className="validation-tabs__item-message">
                {message}
              </span>
              {line && (
                <span className="validation-tabs__item-location">
                  <FormattedMessage
                    {...messages.lineChar}
                    values={{ line, char: column || 1 }}
                  />
                </span>
              )}
            </div>
            {/* Always show redirection icon for errors (even API errors without line numbers) */}
            {/* Clicking it acknowledges the error and enables buttons */}
            <CapTooltip title={line ? `Line ${line}, Char ${column || 1}` : 'Click to acknowledge error and focus editor'}>
              <button
                type="button"
                className="validation-tabs__item-navigate"
                onClick={(e) => handleNavigateClick(issue, e)}
                aria-label={line ? `Line ${line}, Char ${column || 1}` : 'Acknowledge error'}
              >
                <CapIcon type="redirection" />
              </button>
            </CapTooltip>
          </div>
        );
      })}
    </div>
  );
};

ValidationTabContent.propTypes = {
  issues: PropTypes.array,
  onErrorClick: PropTypes.func,
  onExpand: PropTypes.func,
};

ValidationTabContent.defaultProps = {
  issues: [],
  onErrorClick: null,
  onExpand: null,
};

/**
 * ValidationTabs Component
 */
const ValidationTabs = ({
  intl,
  validation,
  onErrorClick,
  isCollapsed = false,
  onToggleCollapse,
  onExpand,
  className,
}) => {
  const [activeKey, setActiveKey] = useState('errors');

  // Group issues into Errors (blocking) and Warnings (non-blocking)
  const { errors, warnings } = useMemo(() => {
    if (!validation) {
      return { errors: [], warnings: [] };
    }
    const allIssues = validation.getAllIssues ? validation.getAllIssues() : [];
    return groupByErrorsAndWarnings(allIssues);
  }, [validation]);

  const errorsCount = errors.length;
  const warningsCount = warnings.length;
  const totalCount = errorsCount + warningsCount;

  // Default active tab: errors if any, else warnings
  useEffect(() => {
    if (errorsCount > 0) {
      setActiveKey('errors');
    } else if (warningsCount > 0) {
      setActiveKey('warnings');
    }
  }, [errorsCount, warningsCount]);

  if (totalCount === 0) {
    return null;
  }

  const tabPanes = [];

  if (errorsCount > 0) {
    tabPanes.push({
      key: 'errors',
      tab: (
        <CapTooltip title={`${intl.formatMessage(messages.errors)} (${errorsCount})`}>
          <span className="validation-tabs__tab-label validation-tabs__tab-label--errors">
            <FormattedMessage {...messages.errors} />
            <span className="validation-tabs__tab-count">({errorsCount})</span>
          </span>
        </CapTooltip>
      ),
      content: (
        <ValidationTabContent
          issues={errors}
          onErrorClick={onErrorClick}
          onExpand={onExpand}
        />
      ),
    });
  }

  if (warningsCount > 0) {
    tabPanes.push({
      key: 'warnings',
      tab: (
        <CapTooltip title={`${intl.formatMessage(messages.warnings)} (${warningsCount})`}>
          <span className="validation-tabs__tab-label validation-tabs__tab-label--warnings">
            <FormattedMessage {...messages.warnings} />
            <span className="validation-tabs__tab-count">({warningsCount})</span>
          </span>
        </CapTooltip>
      ),
      content: (
        <ValidationTabContent
          issues={warnings}
          onErrorClick={onErrorClick}
          onExpand={onExpand}
        />
      ),
    });
  }

  const handleToggleCollapse = () => {
    if (onToggleCollapse) {
      onToggleCollapse();
    }
  };

  const collapseLabel = isCollapsed
    ? intl.formatMessage(messages.expandPanel)
    : intl.formatMessage(messages.collapsePanel);

  return (
    <div className={`validation-tabs ${isCollapsed ? 'validation-tabs--collapsed' : ''} ${className || ''}`}>
      <CapRow className="validation-tabs__header">
        <StyledCapTab
          className="validation-tabs__tabs"
          activeKey={activeKey || (tabPanes[0]?.key)}
          onChange={setActiveKey}
          panes={tabPanes}
        />
        <CapRow className="validation-tabs__actions">
          <CapTooltip title={collapseLabel}>
            <button
              type="button"
              className="validation-tabs__collapse-toggle"
              onClick={handleToggleCollapse}
              aria-label={collapseLabel}
            >
              <CapIcon type={isCollapsed ? 'chevron-up' : 'chevron-down'} />
            </button>
          </CapTooltip>
        </CapRow>
      </CapRow>
    </div>
  );
};

ValidationTabs.propTypes = {
  intl: intlShape.isRequired,
  validation: PropTypes.shape({
    getAllIssues: PropTypes.func,
  }),
  onErrorClick: PropTypes.func,
  isCollapsed: PropTypes.bool,
  onToggleCollapse: PropTypes.func,
  onExpand: PropTypes.func,
  className: PropTypes.string,
};

ValidationTabs.defaultProps = {
  validation: null,
  onErrorClick: null,
  isCollapsed: false,
  onToggleCollapse: null,
  onExpand: null,
  className: '',
};

export default injectIntl(ValidationTabs);
