import { useEffect } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";

interface SubtitleStyleOption {
  id: string;
  label: string;
  font_family?: string;
  font_file?: string;
  font_size?: number;
  highlight_color?: string;
  normal_color?: string;
  stroke_color?: string;
  stroke_size?: number;
  letter_spacing?: number;
  bottom_margin?: number;
  is_default?: boolean;
}

interface TitleStyleOption {
  id: string;
  label: string;
  font_family?: string;
  font_file?: string;
  font_size?: number;
  color?: string;
  stroke_color?: string;
  stroke_size?: number;
  letter_spacing?: number;
  font_weight?: number;
  top_margin?: number;
  is_default?: boolean;
}

interface FloatingStylePreviewProps {
  onClose: () => void;
  videoTitle: string;
  videoSecondaryTitle: string;
  titleStyles: TitleStyleOption[];
  selectedTitleStyleId: string;
  titleFontSize: number;
  selectedSecondaryTitleStyleId: string;
  secondaryTitleFontSize: number;
  secondaryTitleTopMargin: number;
  subtitleStyles: SubtitleStyleOption[];
  selectedSubtitleStyleId: string;
  subtitleFontSize: number;
  titleTopMargin: number;
  subtitleBottomMargin: number;
  enableSubtitles: boolean;
  resolveAssetUrl: (path?: string | null) => string | null;
  getFontFormat: (fontFile?: string) => string;
  buildTextShadow: (color: string, size: number) => string;
  previewBaseWidth: number;
  previewBaseHeight: number;
  previewBackgroundUrl?: string | null;
}

const DESKTOP_WIDTH = 280;
const MOBILE_WIDTH = 160;

export function FloatingStylePreview({
  onClose,
  videoTitle,
  videoSecondaryTitle,
  titleStyles,
  selectedTitleStyleId,
  titleFontSize,
  selectedSecondaryTitleStyleId,
  secondaryTitleFontSize,
  secondaryTitleTopMargin,
  subtitleStyles,
  selectedSubtitleStyleId,
  subtitleFontSize,
  titleTopMargin,
  subtitleBottomMargin,
  enableSubtitles,
  resolveAssetUrl,
  getFontFormat,
  buildTextShadow,
  previewBaseWidth,
  previewBaseHeight,
  previewBackgroundUrl,
}: FloatingStylePreviewProps) {
  const isMobile = typeof window !== "undefined" && window.innerWidth < 640;
  const windowWidth = isMobile ? MOBILE_WIDTH : DESKTOP_WIDTH;

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onClose]);

  const previewScale = windowWidth / previewBaseWidth;
  const previewHeight = previewBaseHeight * previewScale;
  const widthScale = Math.min(1, previewBaseWidth / 1080);
  const responsiveScale = Math.max(0.55, widthScale);

  const activeSubtitleStyle = subtitleStyles.find((s) => s.id === selectedSubtitleStyleId)
    || subtitleStyles.find((s) => s.is_default)
    || subtitleStyles[0];

  const activeTitleStyle = titleStyles.find((s) => s.id === selectedTitleStyleId)
    || titleStyles.find((s) => s.is_default)
    || titleStyles[0];

  const previewTitleText = videoTitle.trim() || "这里是标题预览";
  const subtitleHighlightText = "最近，一个叫Cloudbot";
  const subtitleNormalText = "的开源项目在GitHub上彻底火了";

  const subtitleHighlightColor = activeSubtitleStyle?.highlight_color || "#FFE600";
  const subtitleNormalColor = activeSubtitleStyle?.normal_color || "#FFFFFF";
  const subtitleStrokeColor = activeSubtitleStyle?.stroke_color || "#000000";
  const subtitleStrokeSize = Math.max(1, Math.round((activeSubtitleStyle?.stroke_size ?? 3) * responsiveScale));
  const subtitleLetterSpacing = Math.max(0, (activeSubtitleStyle?.letter_spacing ?? 2) * responsiveScale);
  const subtitleFontFamilyName = `SubtitlePreview-${activeSubtitleStyle?.id || "default"}`;
  const subtitleFontUrl = activeSubtitleStyle?.font_file
    ? resolveAssetUrl(`fonts/${activeSubtitleStyle.font_file}`)
    : null;

  const titleColor = activeTitleStyle?.color || "#FFFFFF";
  const titleStrokeColor = activeTitleStyle?.stroke_color || "#000000";
  const titleStrokeSize = Math.max(1, Math.round((activeTitleStyle?.stroke_size ?? 8) * responsiveScale));
  const titleLetterSpacing = Math.max(0, (activeTitleStyle?.letter_spacing ?? 4) * responsiveScale);
  const titleFontWeight = activeTitleStyle?.font_weight ?? 900;
  const titleFontFamilyName = `TitlePreview-${activeTitleStyle?.id || "default"}`;
  const titleFontUrl = activeTitleStyle?.font_file
    ? resolveAssetUrl(`fonts/${activeTitleStyle.font_file}`)
    : null;

  const scaledTitleFontSize = Math.max(36, Math.round(titleFontSize * responsiveScale));
  const scaledSubtitleFontSize = Math.max(28, Math.round(subtitleFontSize * responsiveScale));
  const scaledTitleTopMargin = Math.max(0, Math.round(titleTopMargin * responsiveScale));
  const scaledSubtitleBottomMargin = Math.max(0, Math.round(subtitleBottomMargin * responsiveScale));

  // 副标题样式
  const activeSecondaryTitleStyle = titleStyles.find((s) => s.id === selectedSecondaryTitleStyleId)
    || activeTitleStyle;
  const stColor = activeSecondaryTitleStyle?.color || "#FFFFFF";
  const stStrokeColor = activeSecondaryTitleStyle?.stroke_color || "#000000";
  const stStrokeSize = Math.max(1, Math.round((activeSecondaryTitleStyle?.stroke_size ?? 6) * responsiveScale));
  const stLetterSpacing = Math.max(0, (activeSecondaryTitleStyle?.letter_spacing ?? 2) * responsiveScale);
  const stFontWeight = activeSecondaryTitleStyle?.font_weight ?? 700;
  const stFontFamilyName = `SecondaryTitlePreview-${activeSecondaryTitleStyle?.id || "default"}`;
  const stFontUrl = activeSecondaryTitleStyle?.font_file
    ? resolveAssetUrl(`fonts/${activeSecondaryTitleStyle.font_file}`)
    : null;
  const scaledSecondaryTitleFontSize = Math.max(24, Math.round(secondaryTitleFontSize * responsiveScale));
  const scaledSecondaryTitleTopMargin = Math.max(0, Math.round(secondaryTitleTopMargin * responsiveScale));
  const previewSecondaryTitleText = videoSecondaryTitle.trim() || "";

  const content = (
    <div
      style={{
        position: "fixed",
        ...(isMobile
          ? { right: "12px", bottom: "12px" }
          : { left: "16px", top: "16px" }),
        width: `${windowWidth}px`,
        zIndex: 150,
        maxHeight: isMobile ? "calc(50dvh)" : "calc(100dvh - 32px)",
        overflow: "hidden",
      }}
      className="rounded-xl border border-white/20 bg-gray-900/95 backdrop-blur-md shadow-2xl"
    >
      {/* 标题栏 */}
      <div
        className="flex items-center justify-between px-3 py-2 border-b border-white/10 select-none"
      >
        <div className="flex items-center gap-2 text-sm text-gray-300">
          <span>样式预览</span>
        </div>
        <button
          onClick={onClose}
          className="p-1 rounded hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
        >
          <X className="h-4 w-4" />
        </button>
      </div>

      {/* 预览内容 */}
      <div
        className="relative overflow-hidden rounded-b-xl"
        style={{ height: `${previewHeight}px` }}
      >
        {(titleFontUrl || subtitleFontUrl || stFontUrl) && (
          <style>{`
            ${titleFontUrl ? `@font-face { font-family: '${titleFontFamilyName}'; src: url('${titleFontUrl}') format('${getFontFormat(activeTitleStyle?.font_file)}'); font-weight: 400; font-style: normal; }` : ''}
            ${stFontUrl && stFontUrl !== titleFontUrl ? `@font-face { font-family: '${stFontFamilyName}'; src: url('${stFontUrl}') format('${getFontFormat(activeSecondaryTitleStyle?.font_file)}'); font-weight: 400; font-style: normal; }` : ''}
            ${subtitleFontUrl ? `@font-face { font-family: '${subtitleFontFamilyName}'; src: url('${subtitleFontUrl}') format('${getFontFormat(activeSubtitleStyle?.font_file)}'); font-weight: 400; font-style: normal; }` : ''}
          `}</style>
        )}
        {previewBackgroundUrl ? (
          <img src={previewBackgroundUrl} alt="" className="absolute inset-0 w-full h-full object-cover" />
        ) : (
          <div className="absolute inset-0 opacity-20 bg-gradient-to-br from-purple-500/40 via-transparent to-pink-500/30" />
        )}
        <div
          className="absolute top-0 left-0"
          style={{
            width: `${previewBaseWidth}px`,
            height: `${previewBaseHeight}px`,
            transform: `scale(${previewScale})`,
            transformOrigin: 'top left',
          }}
        >
          <div
            className="w-full text-center"
            style={{
              position: 'absolute',
              top: `${scaledTitleTopMargin}px`,
              left: 0,
              right: 0,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              padding: '0 5%',
              boxSizing: 'border-box',
            }}
          >
            <div
              style={{
                color: titleColor,
                fontSize: `${scaledTitleFontSize}px`,
                fontWeight: titleFontWeight,
                fontFamily: titleFontUrl
                  ? `'${titleFontFamilyName}', "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif`
                  : '"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif',
                textShadow: buildTextShadow(titleStrokeColor, titleStrokeSize),
                letterSpacing: `${titleLetterSpacing}px`,
                lineHeight: 1.2,
                whiteSpace: 'normal',
                wordBreak: 'break-word',
                overflowWrap: 'anywhere',
                opacity: videoTitle.trim() ? 1 : 0.7,
              }}
            >
              {previewTitleText}
            </div>
            {previewSecondaryTitleText && (
              <div
                style={{
                  marginTop: `${scaledSecondaryTitleTopMargin}px`,
                  color: stColor,
                  fontSize: `${scaledSecondaryTitleFontSize}px`,
                  fontWeight: stFontWeight,
                  fontFamily: stFontUrl && stFontUrl !== titleFontUrl
                    ? `'${stFontFamilyName}', "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif`
                    : titleFontUrl
                      ? `'${titleFontFamilyName}', "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif`
                      : '"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif',
                  textShadow: buildTextShadow(stStrokeColor, stStrokeSize),
                  letterSpacing: `${stLetterSpacing}px`,
                  lineHeight: 1.2,
                  whiteSpace: 'normal',
                  wordBreak: 'break-word',
                  overflowWrap: 'anywhere',
                }}
              >
                {previewSecondaryTitleText}
              </div>
            )}
          </div>

          <div
            className="w-full text-center"
            style={{
              position: 'absolute',
              bottom: `${scaledSubtitleBottomMargin}px`,
              left: 0,
              right: 0,
              fontSize: `${scaledSubtitleFontSize}px`,
              fontFamily: subtitleFontUrl
                ? `'${subtitleFontFamilyName}', "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif`
                : '"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif',
              textShadow: buildTextShadow(subtitleStrokeColor, subtitleStrokeSize),
              letterSpacing: `${subtitleLetterSpacing}px`,
              lineHeight: 1.35,
              whiteSpace: 'normal',
              wordBreak: 'break-word',
              overflowWrap: 'anywhere',
              boxSizing: 'border-box',
              padding: '0 6%',
            }}
          >
            {enableSubtitles ? (
              <>
                <span style={{ color: subtitleHighlightColor }}>{subtitleHighlightText}</span>
                <span style={{ color: subtitleNormalColor }}>{subtitleNormalText}</span>
              </>
            ) : (
              <span className="text-gray-400 text-sm">字幕已关闭</span>
            )}
          </div>
        </div>
      </div>
    </div>
  );

  return createPortal(content, document.body);
}
