"use client"

import { useState } from "react"
import { X } from "lucide-react"
import { Button } from "./ui/button"
import { Card } from "./ui/card"

interface AIRewriteModalProps {
  isOpen: boolean
  onClose: () => void
  originalContent: string
}

export function AIRewriteModal({ isOpen, onClose, originalContent }: AIRewriteModalProps) {
  const [rewrittenContent, setRewrittenContent] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleRewrite = async () => {
    try {
      setIsLoading(true)
      setError(null)
      // 调用实际的AI改写API
      const response = await fetch("/api/ai/rewrite", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ content: originalContent }),
      })

      if (!response.ok) {
        throw new Error("AI改写请求失败")
      }

      const data = await response.json()
      setRewrittenContent(data.rewrittenContent)
    } catch (err) {
      setError(err instanceof Error ? err.message : "改写过程中发生错误")
      console.error("AI改写错误:", err)
    } finally {
      setIsLoading(false)
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <Card className="w-full max-w-lg p-6">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-semibold">AI 内容改写</h2>
          <Button variant="ghost" size="sm" onClick={onClose}>
            <X className="w-4 h-4" />
          </Button>
        </div>
        <div className="space-y-4">
          <div>
            <h3 className="font-medium mb-2">原始内容：</h3>
            <p className="text-sm text-gray-600">{originalContent}</p>
          </div>
          <div>
            <h3 className="font-medium mb-2">改写后内容：</h3>
            <p className="text-sm text-gray-600">{rewrittenContent || '点击"开始改写"按钮生成内容'}</p>
          </div>
        </div>
        <div className="mt-6 flex justify-end space-x-2">
          {error && <p className="text-sm text-red-500 mr-auto">{error}</p>}
          <Button variant="outline" onClick={onClose} disabled={isLoading}>
            取消
          </Button>
          <Button onClick={handleRewrite} disabled={isLoading}>
            {isLoading ? (
              <>
                <span className="mr-2">处理中</span>
                <span className="animate-spin">⟳</span>
              </>
            ) : (
              "开始改写"
            )}
          </Button>
        </div>
      </Card>
    </div>
  )
}
