"use client"

import { Button } from "@/components/ui/button"
import { FileDown, FileText, Copy } from "lucide-react"

interface ExportControlsProps {
  documentUrl: string | null
  onError: (error: string) => void
}

export default function ExportControls({ documentUrl, onError }: ExportControlsProps) {
  const handleDownload = () => {
    if (!documentUrl) {
      onError("没有可下载的文档")
      return
    }

    try {
      // 创建一个临时链接并触发下载
      const link = document.createElement("a")
      link.href = documentUrl
      link.download = "用户数据资产中台使用手册.docx"
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } catch (err) {
      onError(`下载文档时出错: ${err instanceof Error ? err.message : String(err)}`)
    }
  }

  const handlePreview = () => {
    if (!documentUrl) {
      onError("没有可预览的文档")
      return
    }

    try {
      // 在新窗口中打开文档
      window.open(documentUrl, "_blank")
    } catch (err) {
      onError(`预览文档时出错: ${err instanceof Error ? err.message : String(err)}`)
    }
  }

  const handleCopyLink = () => {
    if (!documentUrl) {
      onError("没有可复制的文档链接")
      return
    }

    try {
      // 复制链接到剪贴板
      navigator.clipboard
        .writeText(documentUrl)
        .then(() => {
          alert("文档链接已复制到剪贴板")
        })
        .catch((err) => {
          onError(`复制链接时出错: ${err instanceof Error ? err.message : String(err)}`)
        })
    } catch (err) {
      onError(`复制链接时出错: ${err instanceof Error ? err.message : String(err)}`)
    }
  }

  return (
    <div className="space-y-6">
      {documentUrl ? (
        <div className="space-y-4">
          <div className="flex flex-col sm:flex-row gap-3">
            <Button onClick={handleDownload} className="flex items-center gap-2">
              <FileDown className="h-4 w-4" />
              <span>下载Word文档</span>
            </Button>

            <Button onClick={handlePreview} variant="outline" className="flex items-center gap-2">
              <FileText className="h-4 w-4" />
              <span>预览文档</span>
            </Button>

            <Button onClick={handleCopyLink} variant="outline" className="flex items-center gap-2">
              <Copy className="h-4 w-4" />
              <span>复制链接</span>
            </Button>
          </div>

          <div className="p-4 bg-gray-50 rounded-md border text-sm">
            <p className="font-medium mb-2">文档已生成</p>
            <p className="text-gray-500 break-all">{documentUrl}</p>
          </div>
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500">
          <p>尚未生成文档</p>
          <p className="text-sm mt-2">请先完成文档生成步骤</p>
        </div>
      )}
    </div>
  )
}
