import DualSpreadsheet from '@/component/DualSpreadsheet/DualSpreadsheet'
import React, { useCallback, useRef } from 'react'

interface SpreadsheetViewerProps {
  data: Record<string, any>
  mergedCells: any[]
  dataVersion: number
  templateId: string
  excelFileName?: string
  isExcelLoading: boolean
  onExcelFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void
  onAutoSaveStateChange?: (state: {
    hasUnsavedChanges: boolean
    isSaving: boolean
    manualSave: () => Promise<void>
  }) => void
}

export const SpreadsheetViewer: React.FC<SpreadsheetViewerProps> = ({
  data,
  mergedCells,
  dataVersion,
  templateId,
  excelFileName,
  isExcelLoading,
  onExcelFileChange,
  onAutoSaveStateChange,
}) => {
  // Используем ref для стабильного коллбека
  const onAutoSaveStateChangeRef = useRef(onAutoSaveStateChange)
  onAutoSaveStateChangeRef.current = onAutoSaveStateChange

  const handleEngineReady = useCallback((engine: any) => {
    if (!engine || !onAutoSaveStateChangeRef.current) return

    // Передаем состояние родителю только один раз при инициализации движка
    const state = {
      hasUnsavedChanges: engine.hasUnsavedChanges || false,
      isSaving: engine.isSaving || false,
      manualSave: engine.manualSave || (() => Promise.resolve()),
    }

    onAutoSaveStateChangeRef.current(state)
  }, [])

  return (
    <div className="min-h-0 flex-1">
      <DualSpreadsheet
        key={dataVersion}
        templateData={{ L: data }}
        mergedCells={mergedCells}
        templateId={templateId}
        excelFileName={excelFileName}
        isExcelLoading={isExcelLoading}
        onExcelFileChange={onExcelFileChange}
        onEngineReady={handleEngineReady}
      />
    </div>
  )
}
