import React from 'react';
import { useCurrentFrame, useVideoConfig, spring, interpolate, Sequence } from 'remotion';
import { SLACK } from '../../lib/slack-colors';
import { SENDER_CONFIGS } from '../../slack-types';
import { SlackAvatar } from './SlackAvatar';
import { SlackReactionPill } from './SlackReactionPill';
import type { SlackMessage, SlackReaction } from '../../slack-types';

interface SlackMessageRowProps {
  message: SlackMessage;
  scale: number;
  isConsecutive: boolean;
  visibleReactions: Array<{ reaction: SlackReaction; revealFrame: number }>;
  currentFrame: number;
}

const renderText = (text: string, scale: number): React.ReactNode => {
  const lines = text.split('\n');
  return lines.map((line, lineIdx) => {
    const parts = line.split(/(@\w[\w\s]*\w|\*[^*]+\*|â¢)/g);
    const rendered = parts.map((part, partIdx) => {
      if (part.startsWith('@')) {
        return (
          <span
            key={partIdx}
            style={{
              backgroundColor: SLACK.mention,
              color: SLACK.mentionText,
              borderRadius: Math.round(2 * scale),
              padding: `0 ${Math.round(2 * scale)}px`,
            }}
          >
            {part}
          </span>
        );
      }
      if (part.startsWith('*') && part.endsWith('*')) {
        return (
          <strong key={partIdx} style={{ fontWeight: 700, color: '#FFFFFF' }}>
            {part.slice(1, -1)}
          </strong>
        );
      }
      return <span key={partIdx}>{part}</span>;
    });

    return (
      <React.Fragment key={lineIdx}>
        {rendered}
        {lineIdx < lines.length - 1 && <br />}
      </React.Fragment>
    );
  });
};

export const SlackMessageRow: React.FC<SlackMessageRowProps> = ({
  message,
  scale,
  isConsecutive,
  visibleReactions,
  currentFrame,
}) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const config = SENDER_CONFIGS[message.sender];

  const progress = spring({
    frame,
    fps,
    config: { damping: 18, stiffness: 160, mass: 0.9 },
  });

  const translateY = interpolate(progress, [0, 1], [14 * scale, 0]);
  const opacity = interpolate(progress, [0, 0.25], [0, 1], { extrapolateRight: 'clamp' });

  const avatarSize = Math.round(36 * scale);
  const fontSize = Math.round(15 * scale);
  const nameFontSize = Math.round(15 * scale);
  const tsFontSize = Math.round(12 * scale);
  const badgeFontSize = Math.round(11 * scale);
  const avatarGap = Math.round(10 * scale);

  const paddingH = Math.round(20 * scale);
  const paddingTop = isConsecutive ? Math.round(2 * scale) : Math.round(12 * scale);
  const paddingBottom = Math.round(2 * scale);

  const activeReactions = visibleReactions.filter(
    (r) => currentFrame >= r.revealFrame
  );

  return (
    <div
      style={{
        transform: `translateY(${translateY}px)`,
        opacity,
        paddingLeft: paddingH,
        paddingRight: paddingH,
        paddingTop,
        paddingBottom,
      }}
    >
      <div style={{ display: 'flex', gap: avatarGap, alignItems: 'flex-start' }}>
        <div
          style={{
            width: avatarSize,
            flexShrink: 0,
            paddingTop: isConsecutive ? 0 : Math.round(2 * scale),
          }}
        >
          {!isConsecutive && <SlackAvatar sender={message.sender} size={avatarSize} />}
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          {!isConsecutive && (
            <div
              style={{
                display: 'flex',
                alignItems: 'baseline',
                gap: Math.round(8 * scale),
                marginBottom: Math.round(2 * scale),
                flexWrap: 'wrap',
              }}
            >
              <span
                style={{
                  fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',
                  fontWeight: 700,
                  fontSize: nameFontSize,
                  color: SLACK.nameColor,
                  lineHeight: 1.2,
                }}
              >
                {config.name}
              </span>

              {config.isApp && (
                <span
                  style={{
                    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',
                    fontSize: badgeFontSize,
                    fontWeight: 700,
                    color: SLACK.appBadgeText,
                    backgroundColor: SLACK.appBadgeBg,
                    padding: `${Math.round(1 * scale)}px ${Math.round(4 * scale)}px`,
                    borderRadius: Math.round(3 * scale),
                    lineHeight: 1.4,
                    letterSpacing: 0.2,
                  }}
                >
                  APP
                </span>
              )}

              <span
                style={{
                  fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',
                  fontSize: tsFontSize,
                  color: SLACK.textSecondary,
                  fontWeight: 400,
                }}
              >
                Today
              </span>
            </div>
          )}

          <div
            style={{
              fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',
              fontSize,
              color: SLACK.textPrimary,
              lineHeight: 1.46667,
              fontWeight: 400,
              wordBreak: 'break-word',
            }}
          >
            {renderText(message.text, scale)}
          </div>

          {activeReactions.length > 0 && (
            <div
              style={{
                display: 'flex',
                flexWrap: 'wrap',
                gap: Math.round(4 * scale),
                marginTop: Math.round(6 * scale),
              }}
            >
              {activeReactions.map(({ reaction, revealFrame }, idx) => (
                <Sequence key={idx} from={revealFrame - (currentFrame - frame)} layout="none">
                  <SlackReactionPill reaction={reaction} scale={scale} />
                </Sequence>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
