/**
 * ValidationPanel Component
 * Displays validation errors, warnings, and security issues
 */

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

// Import components individually to avoid undefined imports
import Badge from 'antd/lib/badge';
import Collapse from 'antd/lib/collapse';
import Empty from 'antd/lib/empty';
import Spin from 'antd/lib/spin';

import CapIcon from '@capillarytech/cap-ui-library/CapIcon';

import messages from './messages';
import { BLOCKING_ERROR_RULE_IDS } from '../../constants';
import './_validationPanel.scss';
import { SEVERITY } from './constants';
import { ISSUE_SOURCES } from '../../utils/validationConstants';

const { Panel } = Collapse;
/**
 * ValidationPanel Component
 */
const ValidationPanel = ({
  validation,
  isVisible = true,
  onErrorClick,
  showLineNumbers = true,
  groupBySource = false,
}) => {
  const [activeKeys, setActiveKeys] = useState(['errors', 'warnings']);

  // Group issues by type or source
  const groupedIssues = useMemo(() => {
    if (!validation) return {};

    const allIssues = validation.getAllIssues();

    if (groupBySource) {
      return allIssues.reduce((groups, issue) => {
        const source = issue.source || 'unknown';
        if (!groups[source]) {
          groups[source] = [];
        }
        groups[source].push(issue);
        return groups;
      }, {});
    }
    return {
      errors: allIssues.filter((issue) => issue.severity === SEVERITY.ERROR),
      warnings: allIssues.filter((issue) => issue.severity === SEVERITY.WARNING),
      info: allIssues.filter((issue) => issue.severity === SEVERITY.INFO),
    };
  }, [validation, groupBySource]);

  // 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 === SEVERITY.ERROR) {
      return true;
    }
    // Rule Group #1 errors are blocking
    if (BLOCKING_ERROR_RULE_IDS.includes(rule)) {
      return true;
    }
    return false;
  };

  // Get icon for issue type
  // Blocking errors use error-icon, warnings use warning

  // Get source icon
  const getSourceIcon = (source) => {
    switch (source) {
      case 'htmlhint':
        return <CapIcon type="code" />;
      case 'css-validator':
        return <CapIcon type="code" />;
      case 'security':
        return <CapIcon type="safety" />;
      case 'custom':
        return <CapIcon type="bug" />;
      default:
        return <CapIcon type="info-circle" />;
    }
  };

  // Handle issue click
  const handleIssueClick = (issue) => {
    if (onErrorClick && issue.line) {
      onErrorClick({
        line: issue.line,
        column: issue.column || 1,
        message: issue.message,
        severity: issue.severity,
      });
    }
  };

  // Render issue item
  const renderIssue = (issue, index) => (
    <div
      key={index}
      className={`validation-issue validation-issue--${issue.severity}`}
      onClick={() => handleIssueClick(issue)}
      role="button"
      tabIndex={0}
      onKeyPress={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          handleIssueClick(issue);
        }
      }}
    >

      <div className="validation-issue__content">
        <div className="validation-issue__message">
          {issue.message}
        </div>

        <div className="validation-issue__meta">
          {showLineNumbers && issue.line && (
            <span className="validation-issue__location">
              <FormattedMessage
                {...messages.lineColumn}
                values={{
                  line: issue.line,
                  column: issue.column || 1,
                }} />
            </span>
          )}

          {issue.rule && (
            <span className="validation-issue__rule">
              {issue.rule}
            </span>
          )}

          {issue.source && (
            <span className="validation-issue__source">
              {getSourceIcon(issue.source)}
              {issue.source}
            </span>
          )}
        </div>
      </div>
    </div>
  );

  // Render panel header with count
  const renderPanelHeader = (title, count, severity, issues = []) =>
  // Check if any issue in this group is a blocking error
  // Use blocking error icon only if there are blocking errors, otherwise use warning icon

    (
      <div className="validation-panel__header">
        <span className="validation-panel__title">
          <FormattedMessage {...title} />
        </span>
        {count > 0 && (
          <Badge count={count} style={{ backgroundColor: getSeverityColor(severity) }} />
        )}
      </div>
    )
  ;

  // Get severity color
  const getSeverityColor = (severity) => {
    switch (severity) {
      case 'error': return '#ff4d4f';
      case 'warning': return '#faad14';
      case 'info': return '#1890ff';
      default: return '#666';
    }
  };

  if (!isVisible) {
    return null;
  }

  // Show loading state
  if (validation?.isValidating) {
    return (
      <div className="validation-panel validation-panel--loading">
        <div className="validation-panel__loading">
          <Spin size="small" />
          <span><FormattedMessage {...messages.validating} /></span>
        </div>
      </div>
    );
  }

  // Skip clean state - don't show "No validation issues found" message

  // Render validation issues
  return (
    <div className="validation-panel">
      <div className="validation-panel__summary">
        <div className="validation-panel__summary-item">
          <CapIcon type="exclamation-circle" style={{ color: '#ff4d4f' }} />
          <span>{validation?.summary?.totalErrors || 0}</span>
          <FormattedMessage {...messages.errors} />
        </div>

        <div className="validation-panel__summary-item">
          <CapIcon type="warning" style={{ color: '#faad14' }} />
          <span>{validation?.summary?.totalWarnings || 0}</span>
          <FormattedMessage {...messages.warnings} />
        </div>

        {validation?.summary?.hasSecurityIssues && (
          <div className="validation-panel__summary-item validation-panel__summary-item--security">
            <CapIcon type="safety" style={{ color: '#ff4d4f' }} />
            <FormattedMessage {...messages.securityIssues} />
          </div>
        )}
      </div>

      <Collapse
        activeKey={activeKeys}
        onChange={setActiveKeys}
        className="validation-panel__collapse"
        ghost
      >
        {Object.entries(groupedIssues).map(([key, issues]) => {
          if (!issues || issues.length === 0) return null;

          const isSourceGroup = groupBySource;
          const title = isSourceGroup
            ? { id: `htmlEditor.validation.source.${key}`, defaultMessage: key }
            : messages[key] || { id: `htmlEditor.validation.${key}`, defaultMessage: key };

          const severity = isSourceGroup
            ? (issues.find((i) => i.severity === SEVERITY.ERROR) ? SEVERITY.ERROR
              : issues.find((i) => i.severity === SEVERITY.WARNING) ? SEVERITY.WARNING : SEVERITY.INFO)
            : key;

          return (
            <Panel
              key={key}
              header={renderPanelHeader(title, issues.length, severity, issues)}
              className={`validation-panel__panel validation-panel__panel--${severity}`}
            >
              <div className="validation-panel__issues">
                {issues.length === 0 ? (
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description={<FormattedMessage {...messages.noIssuesOfType} />}
                  />
                ) : (
                  issues.map((issue, index) => renderIssue(issue, index))
                )}
              </div>
            </Panel>
          );
        })}
      </Collapse>

      {validation?.sanitizationWarnings?.length > 0 && (
        <div className="validation-panel__sanitization">
          <div className="validation-panel__sanitization-header">
            <CapIcon type="eye-invisible" />
            <FormattedMessage {...messages.sanitizationWarnings} />
          </div>
          <div className="validation-panel__sanitization-list">
            {validation.sanitizationWarnings.map((warning, index) => (
              <div key={index} className="validation-panel__sanitization-item">
                {warning.message}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

ValidationPanel.propTypes = {
  validation: PropTypes.object,
  isVisible: PropTypes.bool,
  onErrorClick: PropTypes.func,
  showLineNumbers: PropTypes.bool,
  groupBySource: PropTypes.bool,
  variant: PropTypes.oneOf(['email', 'inapp']),
};

export default ValidationPanel;