import { parseExcelFile } from '@/services/fileApiSevice'
import { Template } from '@/types/template'
import React, { useState } from 'react'
import { ExcelUploadPanel } from './ExcelUploadPanel'
import { FormattingToolbar } from './FormattingToolbar'
import { HeaderBar } from './HeaderBar'
import { SpreadsheetViewer } from './SpreadsheetViewer'

interface TemplateEditorProps {
  template: Template
  onBack: () => void
}

export const TemplateEditor: React.FC<TemplateEditorProps> = ({
  template,
  onBack,
}) => {
  const [editedTemplate, setEditedTemplate] = useState(template)
  const [excelData, setExcelData] = useState<Record<string, any>>(
    template.excelData || {}
  )
  const [isLoading, setIsLoading] = useState(false)
  const [dataVersion, setDataVersion] = useState(0)

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    setIsLoading(true)
    try {
      const { fileId, data, mergedCells } = await parseExcelFile(
        file,
        template.id
      )
      setExcelData(data)

      const updatedTemplate = {
        ...template,
        excelFile: file,
        excelData: data,
        mergedCells,
        updatedAt: new Date(),
      }

      setEditedTemplate(updatedTemplate)
      setDataVersion(v => v + 1)

      console.log('✅ Файл загружен с ID:', fileId)
    } catch (err) {
      console.error(err)
      alert('Ошибка при загрузке Excel файла на сервер')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="flex h-screen flex-col bg-background">
      <HeaderBar template={editedTemplate} onBack={onBack} />
      <div className="flex-shrink-0 border-b bg-muted/30 px-4 py-2">
        <div className="flex items-center justify-between">
          <FormattingToolbar />
          <ExcelUploadPanel
            fileName={editedTemplate.excelFile?.name}
            isLoading={isLoading}
            onUploadClick={() => {}}
            onFileChange={handleFileChange}
          />
        </div>
      </div>
      <SpreadsheetViewer
        data={excelData}
        mergedCells={editedTemplate.mergedCells || []}
        dataVersion={dataVersion}
        templateId={editedTemplate.id}
      />
    </div>
  )
}
