import React from 'react';
import { AbsoluteFill, useCurrentFrame, useVideoConfig, staticFile } from 'remotion';
import {
  CaptionsData,
  getCurrentSegment,
  getCurrentWordIndex,
} from '../utils/captions';

/**
 * 字幕样式接口
 * 使用 snake_case 与 Python 后端保持一致
 */
export interface SubtitleStyle {
  font_file?: string;
  font_family?: string;
  font_size?: number;
  highlight_color?: string;
  normal_color?: string;
  stroke_color?: string;
  stroke_size?: number;
  letter_spacing?: number;
  bottom_margin?: number;
}

interface SubtitlesProps {
  captions: CaptionsData;
  style?: SubtitleStyle;
}

/**
 * 逐字高亮字幕组件
 * 根据时间戳逐字高亮显示字幕（无背景，纯文字描边）
 */
const getFontFormat = (fontFile?: string) => {
  if (!fontFile) return 'truetype';
  const ext = fontFile.split('.').pop()?.toLowerCase();
  if (ext === 'otf') return 'opentype';
  return 'truetype';
};

/**
 * 构建描边样式（使用 CSS 原生描边，避免 textShadow 重影）
 */
const buildStrokeStyle = (color: string, size: number): React.CSSProperties => ({
  WebkitTextStroke: `${size}px ${color}`,
  paintOrder: 'stroke fill',
  textShadow: `0 2px 4px rgba(0,0,0,0.4)`,
});

export const Subtitles: React.FC<SubtitlesProps> = ({ captions, style }) => {
  const frame = useCurrentFrame();
  const { fps, width } = useVideoConfig();

  const currentTimeInSeconds = frame / fps;

  // 获取当前段落
  const currentSegment = getCurrentSegment(captions, currentTimeInSeconds);

  if (!currentSegment || currentSegment.words.length === 0) {
    return null;
  }

  // 获取当前高亮字的索引
  const currentWordIndex = getCurrentWordIndex(currentSegment, currentTimeInSeconds);

  // 使用统一的 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 ?? 52;
  const baseStrokeSize = style?.stroke_size ?? 3;
  const baseLetterSpacing = style?.letter_spacing ?? 2;
  const baseBottomMargin = style?.bottom_margin;

  const fontSize = Math.max(28, Math.round(baseFontSize * responsiveScale));
  const highlightColor = style?.highlight_color ?? '#FFFF00';
  const normalColor = style?.normal_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 bottomMargin = typeof baseBottomMargin === 'number'
    ? Math.max(0, Math.round(baseBottomMargin * responsiveScale))
    : undefined;

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

  return (
    <AbsoluteFill
      style={{
        justifyContent: 'flex-end',
        alignItems: 'center',
        paddingBottom: typeof bottomMargin === 'number' ? `${bottomMargin}px` : '6%',
      }}
    >
      {fontFile && (
        <style>{`
          @font-face {
            font-family: '${fontFamilyName}';
            src: url('${staticFile(fontFile)}') format('${getFontFormat(fontFile)}');
            font-weight: 400;
            font-style: normal;
          }
        `}</style>
      )}
      <p
        style={{
          margin: 0,
          fontSize: `${fontSize}px`,
          fontFamily: fontFamilyCss,
          fontWeight: 800,
          lineHeight: 1.4,
          textAlign: 'center',
          width: '100%',
          boxSizing: 'border-box',
          padding: '0 6%',
          whiteSpace: 'normal',
          wordBreak: 'break-word',
          overflowWrap: 'anywhere',
          letterSpacing: `${letterSpacing}px`,
        }}
      >
        {currentSegment.words.map((word, index) => {
          const isHighlighted = index <= currentWordIndex;
          return (
            <span
              key={`${word.word}-${index}`}
              style={{
                color: isHighlighted ? highlightColor : normalColor,
                ...buildStrokeStyle(strokeColor, strokeSize),
                transition: 'color 0.05s ease',
              }}
            >
              {word.word}
            </span>
          );
        })}
      </p>
    </AbsoluteFill>
  );
};
