import React from 'react';
import {
  AbsoluteFill,
  interpolate,
  useCurrentFrame,
  useVideoConfig,
  staticFile,
} from 'remotion';

/**
 * 标题样式接口
 * 使用 snake_case 与 Python 后端保持一致
 */
export interface TitleStyle {
  font_file?: string;
  font_family?: string;
  font_size?: number;
  color?: string;
  stroke_color?: string;
  stroke_size?: number;
  letter_spacing?: number;
  top_margin?: number;
  font_weight?: number;
}

interface TitleProps {
  title: string;
  secondaryTitle?: string;
  duration?: number; // 标题显示时长（秒）
  displayMode?: 'short' | 'persistent'; // 短暂显示或常驻显示
  fadeOutStart?: number; // 开始淡出的时间（秒）
  style?: TitleStyle;
  secondaryTitleStyle?: TitleStyle;
}

/**
 * 片头标题组件
 * 在视频顶部显示标题，带淡入淡出效果
 */
const getFontFormat = (fontFile?: string) => {
  if (!fontFile) return 'truetype';
  const ext = fontFile.split('.').pop()?.toLowerCase();
  if (ext === 'otf') return 'opentype';
  return 'truetype';
};

/**
 * 构建描边样式（使用 CSS 原生描边，避免 textShadow 重影）
 * 返回需要合并到 style 对象上的属性
 */
const buildStrokeStyle = (color: string, size: number): React.CSSProperties => ({
  WebkitTextStroke: `${size}px ${color}`,
  paintOrder: 'stroke fill',
  textShadow: `0 2px 4px rgba(0,0,0,0.3)`,
});

export const Title: React.FC<TitleProps> = ({
  title,
  secondaryTitle,
  duration = 4,
  displayMode = 'short',
  fadeOutStart,
  style,
  secondaryTitleStyle,
}) => {
  const frame = useCurrentFrame();
  const { fps, width } = useVideoConfig();

  const currentTimeInSeconds = frame / fps;

  // 短暂显示：超过设定时长后不再渲染；常驻显示：全程保留
  if (displayMode === 'short' && currentTimeInSeconds > duration) {
    return null;
  }

  // 淡入效果 (0-0.5秒)
  const fadeInOpacity = interpolate(
    currentTimeInSeconds,
    [0, 0.5],
    [0, 1],
    { extrapolateRight: 'clamp' }
  );

  const defaultFadeOutStart = Math.max(duration - 1, 0.5);
  const effectiveFadeOutStart = Math.max(
    0.1,
    Math.min(fadeOutStart ?? defaultFadeOutStart, duration - 0.05)
  );

  // 淡出效果（仅短暂显示模式生效）
  const fadeOutOpacity = displayMode === 'persistent'
    ? 1
    : interpolate(
      currentTimeInSeconds,
      [effectiveFadeOutStart, duration],
      [1, 0],
      { extrapolateLeft: 'clamp', extrapolateRight: 'clamp' }
    );

  const opacity = Math.min(fadeInOpacity, fadeOutOpacity);

  // 轻微的下滑动画
  const translateY = interpolate(
    currentTimeInSeconds,
    [0, 0.5],
    [-20, 0],
    { extrapolateRight: 'clamp' }
  );

  // 使用统一的 snake_case 属性名称
  const fontFile = style?.font_file;
  const fontFamily = style?.font_family;
  const widthScale = Math.min(1, width / 1080);
  const responsiveScale = Math.max(0.55, widthScale);

  const baseFontSize = style?.font_size ?? 72;
  const baseStrokeSize = style?.stroke_size ?? 8;
  const baseLetterSpacing = style?.letter_spacing ?? 4;
  const baseTopMargin = style?.top_margin;

  const fontSize = Math.max(36, Math.round(baseFontSize * responsiveScale));
  const color = style?.color ?? '#FFFFFF';
  const strokeColor = style?.stroke_color ?? '#000000';
  const strokeSize = Math.max(1, Math.round(baseStrokeSize * responsiveScale));
  const letterSpacing = Math.max(0, baseLetterSpacing * responsiveScale);
  const topMargin = typeof baseTopMargin === 'number'
    ? Math.max(0, Math.round(baseTopMargin * responsiveScale))
    : undefined;
  const fontWeight = style?.font_weight ?? 900;

  const fontFamilyName = fontFamily || 'TitleFont';
  const fontFamilyCss = fontFile
    ? `'${fontFamilyName}'`
    : '"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif';

  // 副标题样式
  const stStyle = secondaryTitleStyle || style;
  const stFontFile = secondaryTitleStyle?.font_file ?? style?.font_file;
  const stFontFamily = secondaryTitleStyle?.font_family ?? style?.font_family;
  const stBaseFontSize = stStyle?.font_size ?? 48;
  const stBaseStrokeSize = stStyle?.stroke_size ?? 3;
  const stBaseLetterSpacing = stStyle?.letter_spacing ?? 2;
  const stBaseTopMargin = secondaryTitleStyle?.top_margin;
  const stFontSize = Math.max(24, Math.round(stBaseFontSize * responsiveScale));
  const stColor = stStyle?.color ?? '#FFFFFF';
  const stStrokeColor = stStyle?.stroke_color ?? '#000000';
  const stStrokeSize = Math.max(1, Math.round(stBaseStrokeSize * responsiveScale));
  const stLetterSpacing = Math.max(0, stBaseLetterSpacing * responsiveScale);
  const stFontWeight = stStyle?.font_weight ?? 700;
  const stFontFamilyName = stFontFamily || 'SecondaryTitleFont';
  const stFontFamilyCss = stFontFile
    ? `'${stFontFamilyName}'`
    : '"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif';
  const stMarginTop = typeof stBaseTopMargin === 'number'
    ? Math.max(0, Math.round(stBaseTopMargin * responsiveScale))
    : Math.round(12 * responsiveScale);

  return (
    <AbsoluteFill
      style={{
        flexDirection: 'column',
        justifyContent: 'flex-start',
        alignItems: 'center',
        paddingTop: typeof topMargin === 'number' ? `${topMargin}px` : '6%',
        opacity,
      }}
    >
      {fontFile && (
        <style>{`
          @font-face {
            font-family: '${fontFamilyName}';
            src: url('${staticFile(fontFile)}') format('${getFontFormat(fontFile)}');
            font-weight: 400;
            font-style: normal;
          }
        `}</style>
      )}
      {secondaryTitle && stFontFile && stFontFile !== fontFile && (
        <style>{`
          @font-face {
            font-family: '${stFontFamilyName}';
            src: url('${staticFile(stFontFile)}') format('${getFontFormat(stFontFile)}');
            font-weight: 400;
            font-style: normal;
          }
        `}</style>
      )}
      <h1
        style={{
          transform: `translateY(${translateY}px)`,
          textAlign: 'center',
          color,
          fontSize: `${fontSize}px`,
          fontWeight,
          fontFamily: fontFamilyCss,
          ...buildStrokeStyle(strokeColor, strokeSize),
          margin: 0,
          width: '100%',
          boxSizing: 'border-box',
          padding: '0 5%',
          lineHeight: 1.3,
          whiteSpace: 'normal',
          wordBreak: 'break-word',
          overflowWrap: 'anywhere',
          letterSpacing: `${letterSpacing}px`,
        }}
      >
        {title}
      </h1>
      {secondaryTitle && (
        <h2
          style={{
            transform: `translateY(${translateY}px)`,
            textAlign: 'center',
            color: stColor,
            fontSize: `${stFontSize}px`,
            fontWeight: stFontWeight,
            fontFamily: stFontFile && stFontFile !== fontFile ? stFontFamilyCss : fontFamilyCss,
            ...buildStrokeStyle(stStrokeColor, stStrokeSize),
            margin: 0,
            marginTop: `${stMarginTop}px`,
            width: '100%',
            boxSizing: 'border-box',
            padding: '0 5%',
            lineHeight: 1.3,
            whiteSpace: 'normal',
            wordBreak: 'break-word',
            overflowWrap: 'anywhere',
            letterSpacing: `${stLetterSpacing}px`,
          }}
        >
          {secondaryTitle}
        </h2>
      )}
    </AbsoluteFill>
  );
};
