import React from 'react'
import { Markdown } from '@/components/editor/Markdown/Markdown'
import type { FileItem } from '@/lib/api'
import type { TOCItem } from '@/lib/utils'
import { useMarkdownDisplay, useTabStore } from '@/stores'

interface MarkdownTabPageProps {
  file: FileItem
  onTocUpdated?: (toc: TOCItem[]) => void
}

export const MarkdownTabPage: React.FC<MarkdownTabPageProps> = ({ 
  file, 
  onTocUpdated 
}) => {
  const { zoom } = useMarkdownDisplay()
  const tab = useTabStore(state => state.tabs.get(file.path))
  
  const content = tab?.content || ''
  const unsavedContent = tab?.unsavedContent || ''
  const isEditing = tab?.isEditing || false
  const loading = tab?.loading || false

  const displayContent = isEditing ? unsavedContent : content

  const handleChange = (newContent: string) => {
    useTabStore.getState().setUnsavedContent(file.path, newContent)
  }

  return (
    <div
      className="w-full px-10 py-4"
      style={{ zoom: zoom / 100 }}
    >
      <div className="h-full w-full">
        {loading ? (
          <div className="p-4 text-gray-400">加载中...</div>
        ) : (
          <Markdown
            key={file.path}
            content={displayContent}
            filePath={file.path}
            onChange={isEditing ? handleChange : undefined}
            readOnly={!isEditing}
            onTocUpdated={onTocUpdated}
          />
        )}
        {!isEditing && <div className="h-24" />}
      </div>
    </div>
  )
}
