import { MergedCell } from '@/type/template'
import { CSSProperties } from 'react'
import { VariableSizeGrid } from 'react-window'

export const ROW_COUNT = 150
export const COL_COUNT = 26
export const ROW_HEIGHT = 28

export const SHEET_NAMES = {
  report: 'L',
  calculations: 'R',
} as const

export type SheetType = keyof typeof SHEET_NAMES

// Добавляем массив типов листов для итерации
export const SHEET_TYPES: SheetType[] = ['report', 'calculations']

// Интерфейс для подсвеченной ячейки
export interface HighlightedCell {
  sheet: string // нормализованное имя листа ('L' или 'R')
  row: number
  col: number
  color: string // класс CSS для цвета подсветки
}

// Интерфейс для области выделения
export interface CellSelection {
  startRow: number
  startCol: number
  endRow: number
  endCol: number
}

// Кэшированные данные ячеек для оптимизации
export interface CachedCellData {
  displayValue: string
  rawValue: string
  isModified: boolean
  nextContentCol: number // индекс ближайшей занятой колонки (COL_COUNT, если нет)
  availablePx: number // суммарная ширина, куда можно расширяться
}

export interface DualSpreadsheetProps {
  templateData?: Record<string, Record<string, any>>
  mergedCells?: MergedCell[] // Добавляем поддержку объединенных ячеек
  templateId?: string // Добавляем ID шаблона для сохранения
  onEngineReady?: (engine: any) => void // Коллбэк, который отдаёт родителю методы движка
  // Пропсы для ExcelUploadPanel
  excelFileName?: string
  isExcelLoading?: boolean
  onExcelFileChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
}

export interface CellProps {
  sheetType: SheetType
  rowIndex: number
  colIndex: number
  columnWidth: number
  columnWidths: number[]
  isSelected: boolean
  isInMultiSelection: boolean
  multiSelectionActive: boolean
  isEditing: boolean
  displayValue: string
  rawValue: string
  isModified: boolean
  availablePx: number
  onCellClick: (row: number, col: number, event?: React.MouseEvent) => void
  onCellDoubleClick: (row: number, col: number) => void
  onCellValueChange: (newValue: string) => void
  onCellReferenceClick?: (
    sheetType: SheetType,
    row: number,
    col: number
  ) => void
  onCellMouseDown?: (row: number, col: number, event: React.MouseEvent) => void
  onCellMouseEnter?: (row: number, col: number) => void
  onCellMouseUp?: () => void
  isInEditMode: boolean
  stopEditing: (save: boolean) => void
  setActiveSheet: (type: SheetType) => void
  activeCellRef: React.RefObject<HTMLInputElement | null>
  style: CSSProperties
  mergedCellInfo?: {
    isMerged: boolean
    isMainCell: boolean
    rowSpan?: number
    colSpan?: number
  }
  isCopied?: boolean
  isCut?: boolean
  highlightColor?: string
}

export interface FormulaBarProps {
  sheetType: SheetType
  activeSheet: SheetType
  selectedCell: { row: number; col: number } | null
  formulaBarValue: string
  isCalculating: boolean
  isEditing: boolean
  onValueChange: (value: string) => void
  onFocus: () => void
  onBlur: (e: React.FocusEvent<HTMLInputElement>) => void
  onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void
  formulaBarRef: (el: HTMLInputElement | null) => void
  // Обновляем props для сохранения
  isSaving?: boolean
  isLoading?: boolean
  hasUnsavedChanges?: boolean
  lastSaveError?: string | null
  onManualSave?: () => void
  onClearError?: () => void
  // Пропсы для ExcelUploadPanel
  excelFileName?: string
  isExcelLoading?: boolean
  onExcelFileChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
}

export interface CellRendererData {
  sheetType: SheetType
  widths: number[]
  selectedCell: { row: number; col: number } | null
  multiSelection: CellSelection[]
  activeSheet: SheetType
  isEditing: boolean
  editingValue: string
  cachedData: Record<string, CachedCellData>
  mergedCells?: MergedCell[]
  highlightedCells: HighlightedCell[] // Добавляем подсвеченные ячейки
  multiSelectionActive: boolean
  handleCellClick: (row: number, col: number, event?: React.MouseEvent) => void
  handleCellDoubleClick: (row: number, col: number) => void
  handleCellChange: (newValue: string) => void
  handleCellReferenceClick?: (
    sheetType: SheetType,
    row: number,
    col: number
  ) => void // Клик для вставки ссылки
  handleCellMouseDown?: (
    row: number,
    col: number,
    event: React.MouseEvent
  ) => void
  handleCellMouseEnter?: (row: number, col: number) => void
  handleCellMouseUp?: () => void
  isInEditMode: boolean // Глобальный режим редактирования
  stopEditing: (save: boolean) => void
  setActiveSheet: (type: SheetType) => void
  activeCellInputRef: React.RefObject<HTMLInputElement | null>
  copiedCells?: {
    data: { row: number; col: number; value: string; rawValue: string }[]
    sourceSheet: SheetType
    isCut: boolean
  } | null
}

export interface CellRendererProps {
  columnIndex: number
  rowIndex: number
  style: CSSProperties
  data: CellRendererData
}

export interface SpreadsheetProps {
  sheetType: SheetType
  columnWidths: number[]
  spreadsheetWidths: { L: number; R: number }
  getCachedCellData: (sheetType: SheetType) => Record<string, CachedCellData>
  selectedCell: { row: number; col: number } | null
  multiSelection: CellSelection[]
  activeSheet: SheetType
  isEditing: boolean
  editingValue: string
  highlightedCells: HighlightedCell[] // Добавляем подсвеченные ячейки
  handleCellClick: (row: number, col: number, event?: React.MouseEvent) => void
  handleCellDoubleClick: (row: number, col: number) => void
  handleCellChange: (newValue: string) => void
  handleCellReferenceClick?: (
    sheetType: SheetType,
    row: number,
    col: number
  ) => void // Клик для вставки ссылки
  handleCellMouseDown?: (
    row: number,
    col: number,
    event: React.MouseEvent
  ) => void
  handleCellMouseEnter?: (row: number, col: number) => void
  handleCellMouseUp?: () => void
  isInEditMode: boolean // Глобальный режим редактирования
  stopEditing: (save: boolean) => void
  setActiveSheet: (type: SheetType) => void
  activeCellInputRef: React.RefObject<HTMLInputElement | null>
  containerRefs: React.MutableRefObject<
    Record<SheetType, HTMLDivElement | null>
  >
  handleKeyDown: (e: React.KeyboardEvent) => void
  headerRefs: React.MutableRefObject<Record<SheetType, HTMLDivElement | null>>
  rowHeaderRefs: React.MutableRefObject<
    Record<SheetType, HTMLDivElement | null>
  >
  gridRefs: React.MutableRefObject<Record<SheetType, VariableSizeGrid | null>>
  onGridScroll: (
    sheetType: SheetType,
    params: { scrollLeft: number; scrollTop: number }
  ) => void
  handleColumnResize: (
    sheetType: SheetType,
    colIndex: number,
    newWidth: number
  ) => void
  mergedCells?: MergedCell[] // Добавляем поддержку объединенных ячеек
  copiedCells?: {
    data: { row: number; col: number; value: string; rawValue: string }[]
    sourceSheet: SheetType
    isCut: boolean
  } | null
}

export interface MergedCellInfo {
  isMerged: boolean
  isMainCell: boolean
  mergedCell?: MergedCell
  spans?: { rowSpan: number; colSpan: number }
}
