"use client"

import { useState, useRef, useEffect } from "react"
import { Card } from "@/components/ui/card"
import { captureScreenshot } from "@/lib/documentation/screenshot-service"

interface ScreenshotCaptureProps {
  pages: Array<{ path: string; title: string; description: string }>
  isCapturing: boolean
  onScreenshotCaptured: (path: string, dataUrl: string) => void
  onCaptureComplete: () => void
  onError: (error: string) => void
}

export default function ScreenshotCapture({
  pages,
  isCapturing,
  onScreenshotCaptured,
  onCaptureComplete,
  onError,
}: ScreenshotCaptureProps) {
  const [currentPageIndex, setCurrentPageIndex] = useState(-1)
  const [currentStatus, setCurrentStatus] = useState("")
  const iframeRef = useRef<HTMLIFrameElement>(null)
  const baseUrl = typeof window !== "undefined" ? window.location.origin : ""

  useEffect(() => {
    if (isCapturing && pages.length > 0) {
      // 开始捕获过程
      setCurrentPageIndex(0)
    } else if (!isCapturing) {
      setCurrentPageIndex(-1)
      setCurrentStatus("")
    }
  }, [isCapturing, pages])

  useEffect(() => {
    if (currentPageIndex >= 0 && currentPageIndex < pages.length) {
      const capturePage = async () => {
        const page = pages[currentPageIndex]
        const fullPath = `${baseUrl}${page.path}`

        try {
          setCurrentStatus(`正在加载页面: ${page.title}`)

          // 等待iframe加载完成
          if (iframeRef.current) {
            iframeRef.current.src = fullPath

            // 监听iframe加载完成事件
            const handleLoad = async () => {
              try {
                setCurrentStatus(`正在捕获页面: ${page.title}`)

                // 给页面一些时间完全渲染
                await new Promise((resolve) => setTimeout(resolve, 2000))

                // 捕获截图
                const screenshot = await captureScreenshot(iframeRef.current!)
                onScreenshotCaptured(page.path, screenshot)

                // 移动到下一页
                if (currentPageIndex < pages.length - 1) {
                  setCurrentPageIndex(currentPageIndex + 1)
                } else {
                  // 所有页面都已捕获
                  onCaptureComplete()
                }
              } catch (err) {
                onError(`捕获页面 ${page.title} 截图时出错: ${err instanceof Error ? err.message : String(err)}`)
              }
            }

            iframeRef.current.onload = handleLoad
          }
        } catch (err) {
          onError(`加载页面 ${page.title} 时出错: ${err instanceof Error ? err.message : String(err)}`)

          // 尝试继续下一页
          if (currentPageIndex < pages.length - 1) {
            setCurrentPageIndex(currentPageIndex + 1)
          } else {
            onCaptureComplete()
          }
        }
      }

      capturePage()
    }
  }, [currentPageIndex, pages, onScreenshotCaptured, onCaptureComplete, onError, baseUrl])

  return (
    <div className="space-y-4">
      {isCapturing && currentPageIndex >= 0 && currentPageIndex < pages.length && (
        <div className="space-y-2">
          <p className="text-sm text-gray-500">{currentStatus}</p>
          <p className="text-sm font-medium">
            正在处理: {currentPageIndex + 1} / {pages.length} - {pages[currentPageIndex].title}
          </p>

          <Card className="overflow-hidden border-2 border-blue-200 bg-blue-50">
            <div className="relative pt-[56.25%]">
              {" "}
              {/* 16:9 宽高比 */}
              <iframe ref={iframeRef} className="absolute top-0 left-0 w-full h-full" title="页面预览" />
            </div>
          </Card>
        </div>
      )}

      {!isCapturing && (
        <div className="text-center py-8 text-gray-500">
          <p>点击"开始捕获"按钮开始截图过程</p>
          <p className="text-sm mt-2">将依次捕获 {pages.length} 个页面的截图</p>
        </div>
      )}
    </div>
  )
}
