import { useEffect, useState } from 'react';
import { buildChatSaveThumbnailUrl, fetchPreviewAsset } from '../api/client';
import type { ChatSaveAnalysis } from '../types';

export function PageSavePreviewPanel({
  sessionId,
  messageId,
  selectedLinkIndex,
  title,
  summary,
  analysis,
  thumbnailVersion,
  onPreviewHoverChange,
}: {
  sessionId: string;
  messageId: string;
  selectedLinkIndex: number;
  title: string;
  summary: string;
  analysis: ChatSaveAnalysis;
  thumbnailVersion: number;
  onPreviewHoverChange?: (locked: boolean) => void;
}) {
  const [thumbnailSrc, setThumbnailSrc] = useState<string | null>(null);
  const [thumbnailFailed, setThumbnailFailed] = useState(false);
  const [previewFailed, setPreviewFailed] = useState(false);

  const pagePreviewUrl = analysis.localPreviewUrl ?? analysis.previewFrameUrl;

  useEffect(() => {
    setPreviewFailed(false);
  }, [pagePreviewUrl]);

  useEffect(() => {
    if (!analysis.hasHtmlContent) {
      setThumbnailSrc(null);
      setThumbnailFailed(false);
      return undefined;
    }

    let objectUrl: string | null = null;
    let cancelled = false;

    const loadThumbnail = async () => {
      setThumbnailFailed(false);
      const apiUrl = buildChatSaveThumbnailUrl({
        sessionId,
        messageId,
        selectedLinkIndex,
        previewTitle: title,
        previewSummary: summary,
        cacheKey: thumbnailVersion,
      });

      try {
        objectUrl = await fetchPreviewAsset(apiUrl);
        if (!cancelled) setThumbnailSrc(objectUrl);
        return;
      } catch {
        if (cancelled) return;
        if (analysis.localThumbnailUrl) {
          setThumbnailSrc(`${analysis.localThumbnailUrl}?v=${thumbnailVersion}`);
          return;
        }
        setThumbnailSrc(null);
        setThumbnailFailed(true);
      }
    };

    void loadThumbnail();

    return () => {
      cancelled = true;
      if (objectUrl) URL.revokeObjectURL(objectUrl);
    };
  }, [
    analysis.hasHtmlContent,
    analysis.localThumbnailUrl,
    messageId,
    selectedLinkIndex,
    sessionId,
    summary,
    thumbnailVersion,
    title,
  ]);

  if (!analysis.hasHtmlContent) {
    return (
      <div className="page-save-error">
        本地未找到页面文件，请确认 Agent 已将 HTML 保存到 MindSpace 工作区。
      </div>
    );
  }

  if (!pagePreviewUrl) {
    return <div className="page-save-error">无法构建页面预览地址。</div>;
  }

  return (
    <div className="page-save-preview-dual">
      <div
        className="page-save-preview-pane page-save-preview-pane-page"
        onMouseEnter={() => onPreviewHoverChange?.(true)}
        onMouseLeave={() => onPreviewHoverChange?.(false)}
        onWheelCapture={(event) => event.stopPropagation()}
      >
        <span className="page-save-preview-label">页面效果</span>
        <p className="page-save-preview-hint">微型页面，可上下滑动查看完整效果</p>
        <div className="page-save-mini-page">
          {!previewFailed ? (
            <iframe
              title="页面预览"
              src={pagePreviewUrl}
              className="page-save-mini-page-frame"
              sandbox="allow-scripts"
              scrolling="yes"
              onError={() => setPreviewFailed(true)}
            />
          ) : (
            <div className="page-save-card-thumb-placeholder">页面预览加载失败</div>
          )}
        </div>
      </div>
      <div className="page-save-preview-pane page-save-preview-pane-thumb">
        <span className="page-save-preview-label">卡片预览图</span>
        <p className="page-save-preview-hint">保存后在信息流中显示的 3:4 封面</p>
        <div className="page-save-card-thumb">
          {thumbnailSrc && !thumbnailFailed ? (
            <img
              src={thumbnailSrc}
              alt={`${title || '页面'} 卡片预览图`}
              onError={() => setThumbnailFailed(true)}
            />
          ) : (
            <span className="page-save-card-thumb-placeholder">
              {thumbnailFailed ? '预览图生成失败' : '正在生成预览图…'}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}
