// app/(editor)/document/[id]/page.tsx
'use client'

import { useState, useEffect } from 'react'
import { Layout, message } from 'antd'
import MonacoEditor from '@/app/components/Editor/MonacoEditor'
import EditorToolbar from '@/app/components/Editor/EditorToolbar'
import FileTree from '@/app/components/FileTree/FileTree'
import { DocumentService } from '@/app/lib/services/document'

const { Sider, Content } = Layout

interface EditorPageProps {
  params: {
    id: string
  }
}

export default function EditorPage({ params }: EditorPageProps) {
  const [content, setContent] = useState('')
  const [loading, setLoading] = useState(true)

  // 加载文档内容
  useEffect(() => {
    const loadDocument = async () => {
      try {
        const doc = await DocumentService.getDocument(params.id)
        setContent(doc.content)
      } catch (error) {
        message.error('加载文档失败'+error)
      } finally {
        setLoading(false)
      }
    }

    loadDocument()
  }, [params.id])

  const handleSave = async () => {
    try {
      await DocumentService.saveDocument({
        id: params.id,
        content,
      })
      message.success('保存成功')
    } catch (error) {
      message.error('保存失败'+error)
    }
  }

  const handleFormat = (type: string) => {
    // TODO: 实现格式化功能
    console.log('Formatting:', type)
  }

  if (loading) {
    return <div>Loading...</div>
  }

  return (
    <Layout className="h-screen">
      <Sider width={250} className="bg-white border-r">
        <FileTree />
      </Sider>
      <Layout>
        <EditorToolbar onSave={handleSave} onFormat={handleFormat} />
        <Content>
          <div className="h-full">
            <MonacoEditor
              docId={params.id}
              defaultValue={content}
              onContentChange={setContent}
            />
          </div>
        </Content>
      </Layout>
    </Layout>
  )
}