import React, { memo, useMemo, useCallback } from 'react';
import { useRealtime } from '../../contexts/RealtimeContext';

// Константы вне компонента
const BASE_CELL_STYLES = {
  width: '100%',
  height: '100%',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  boxSizing: 'border-box',
  position: 'absolute',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  border: '2px solid transparent',
  padding: '8px',
};

const LOCKED_STYLES = {
  border: '2px solid #e0e0e0',
  backgroundColor: '#f5f5f5',
  cursor: 'not-allowed',
  opacity: 0.85,
};

const LOCK_BADGE_STYLES = {
  position: 'absolute',
  top: '2px',
  right: '2px',
  background: 'rgba(0, 0, 0, 0.7)',
  color: 'white',
  fontSize: '9px',
  padding: '1px 4px',
  borderRadius: '3px',
  pointerEvents: 'none',
  zIndex: 10,
  fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
  letterSpacing: '0.3px',
  backdropFilter: 'blur(4px)',
  border: '1px solid rgba(255, 255, 255, 0.1)',
};

const CONTAINER_STYLES = {
  display: '-webkit-box',
  WebkitBoxOrient: 'vertical',
  WebkitLineClamp: 3,
  overflow: 'hidden',
  whiteSpace: 'pre-wrap',
  wordBreak: 'break-word',
};

const INTEGER_COLUMN_IDS = new Set([
  'data.header.num_group',
  'data.nomenclature_group_id',
  'data.header.item_id',
  'data.article_id',
  'data.code_razdela',
]);

const getColorBrightness = (hexColor) => {
  if (!hexColor) return 255;
  const color = hexColor.replace('#', '');
  let r, g, b;
  if (color.length === 3) {
    r = parseInt(color[0] + color[0], 16);
    g = parseInt(color[1] + color[1], 16);
    b = parseInt(color[2] + color[2], 16);
  } else if (color.length === 6) {
    r = parseInt(color.substring(0, 2), 16);
    g = parseInt(color.substring(2, 4), 16);
    b = parseInt(color.substring(4, 6), 16);
  } else {
    return 255;
  }
  return (0.299 * r + 0.587 * g + 0.114 * b);
};

const formatNumber = (value, asInteger = false) => {
  if (value === null || value === undefined || value === '') return String(value || '');
  const num = Number(value);
  if (isNaN(num)) return String(value);
  return num.toLocaleString('ru-RU', {
    minimumFractionDigits: asInteger ? 0 : 1,
    maximumFractionDigits: asInteger ? 0 : 1,
    useGrouping: true,
  });
};

// Оптимизированная функция подсветки
const createHighlightedContent = (originalValue, displayValue, searchQueries) => {
  const cleanQueries = searchQueries.filter(Boolean);
  if (cleanQueries.length === 0) return displayValue;

  const searchStr = String(originalValue ?? displayValue);
  const escapedQueries = cleanQueries.map(q => q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
  const regex = new RegExp(`(${escapedQueries.join('|')})`, 'gi');

  if (!regex.test(searchStr)) return displayValue;

  const parts = searchStr.split(regex);
  return parts.map((part, index) => {
    if (!regex.test(part)) return part;
    return React.createElement('mark', {
      key: index,
      style: {
        backgroundColor: '#ffeb3b',
        color: '#000',
        fontWeight: 'bold',
        padding: '0 2px',
        borderRadius: '2px',
      },
    }, part);
  });
};

const CellComponent = ({
  cell,
  row,
  column,
  onClick,
  globalFilter,
  columnFilter,
  backgroundColor,
  color,
  isEditable,
  isUpdating,
  onCellNumberClick,
}) => {
  const { lockedCells } = useRealtime();
  const cellKey = `${row.id}_${column.id}`;
  const isLocked = lockedCells.includes(cellKey);

  // Мемоизация значения
  const { rawValue, displayValue, isNumeric } = useMemo(() => {
    const value = cell.getValue();
    const isNum = !isNaN(Number(value)) && value !== null && value !== undefined && value !== '';
    let display = String(value || '');

    if (isNum) {
      const asInteger = INTEGER_COLUMN_IDS.has(column.id);
      display = formatNumber(value, asInteger);
    }

    return { rawValue: value, displayValue: display, isNumeric: isNum };
  }, [cell, column.id]);

  const highlightedContent = useMemo(() => {
    const searchQueries = [globalFilter, columnFilter];
    return createHighlightedContent(rawValue, displayValue, searchQueries);
  }, [rawValue, displayValue, globalFilter, columnFilter]);

  const textColor = useMemo(() => {
    if (isLocked) return '#999999';
    const brightness = getColorBrightness(backgroundColor);
    return brightness < 128 ? '#ffffff' : '#000000';
  }, [backgroundColor, isLocked]);

  const cellStyles = useMemo(() => ({
    ...BASE_CELL_STYLES,
    backgroundColor: isLocked ? '#f5f5f5' : backgroundColor,
    color: textColor,
    ...(isLocked ? LOCKED_STYLES : {}),
  }), [backgroundColor, isLocked, textColor]);

  const lockBadge = useMemo(() => {
    if (!isLocked) return null;
    return <div style={LOCK_BADGE_STYLES}>🔒</div>;
  }, [isLocked]);

  const handleClick = useCallback(() => {
    if (!isLocked && onClick) {
      onClick();
    }
  }, [isLocked, onClick]);

  return (
    <div
      className="cell"
      style={cellStyles}
      onClick={handleClick}
    >
      <span style={CONTAINER_STYLES}>{highlightedContent}</span>
      {lockBadge}
    </div>
  );
};

const Cell = React.memo(CellComponent, (prevProps, nextProps) => {
  // Возвращаем true если пропсы равны (не нужно перерендеривать)
  return (
    prevProps.cell.getValue() === nextProps.cell.getValue() &&
    prevProps.row.id === nextProps.row.id &&
    prevProps.column.id === nextProps.column.id &&
    prevProps.globalFilter === nextProps.globalFilter &&
    prevProps.columnFilter === nextProps.columnFilter &&
    prevProps.backgroundColor === nextProps.backgroundColor &&
    prevProps.isEditable === nextProps.isEditable &&
    prevProps.isUpdating === nextProps.isUpdating &&
    prevProps.onCellNumberClick === nextProps.onCellNumberClick
  );
});

export default Cell;