/**
 * File Mention Tag Component
 *
 * 显示文件提及的标签样式组件
 */

import { File, Folder, X } from 'lucide-react';
import { cn } from '../utils/cn.js';

export interface FileMentionTagProps {
  /** 文件路径 */
  path: string;
  /** 是否可删除 */
  removable?: boolean;
  /** 删除回调 */
  onRemove?: () => void;
  /** 点击回调 */
  onClick?: () => void;
  /** 尺寸 */
  size?: 'sm' | 'md';
  /** 额外的 class */
  className?: string;
}

// 根据扩展名获取图标颜色
function getFileColor(path: string): string {
  const ext = path.split('.').pop()?.toLowerCase();
  const colors: Record<string, string> = {
    ts: 'text-blue-400',
    tsx: 'text-blue-400',
    js: 'text-yellow-400',
    jsx: 'text-yellow-400',
    json: 'text-yellow-500',
    md: 'text-fg-muted',
    css: 'text-pink-400',
    scss: 'text-pink-400',
    html: 'text-orange-400',
    py: 'text-green-400',
    go: 'text-cyan-400',
    rs: 'text-orange-500',
    vue: 'text-emerald-400',
    svelte: 'text-orange-500',
  };
  return colors[ext || ''] || 'text-fg-muted';
}

// 判断是否是目录
function isDirectory(path: string): boolean {
  return path.endsWith('/');
}

// 获取文件名
function getFileName(path: string): string {
  const parts = path.replace(/\/$/, '').split('/');
  return parts[parts.length - 1] || path;
}

export function FileMentionTag({
  path,
  removable = false,
  onRemove,
  onClick,
  size = 'md',
  className,
}: FileMentionTagProps) {
  const isDir = isDirectory(path);
  const fileName = getFileName(path);
  const iconColor = isDir ? 'text-yellow-400' : getFileColor(path);

  const sizeClasses = {
    sm: 'text-xs px-1.5 py-0.5 gap-1',
    md: 'text-sm px-2 py-1 gap-1.5',
  };

  const iconSize = size === 'sm' ? 10 : 12;

  return (
    <span
      className={cn(
        'inline-flex items-center rounded-md',
        'bg-primary-600/20 text-primary-300 border border-primary-600/30',
        'font-mono',
        sizeClasses[size],
        onClick && 'cursor-pointer hover:bg-primary-600/30 transition-colors',
        className
      )}
      onClick={onClick}
    >
      {isDir ? (
        <Folder size={iconSize} className={iconColor} />
      ) : (
        <File size={iconSize} className={iconColor} />
      )}
      <span className="truncate max-w-[200px]" title={path}>
        {fileName}
      </span>
      {removable && onRemove && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            onRemove();
          }}
          className="ml-0.5 p-0.5 rounded hover:bg-primary-600/40 transition-colors"
        >
          <X size={iconSize} />
        </button>
      )}
    </span>
  );
}

/**
 * 解析文本中的文件提及
 * 返回分段后的内容数组
 */
export interface ParsedSegment {
  type: 'text' | 'file';
  content: string;
}

export function parseFileMentions(text: string): ParsedSegment[] {
  const segments: ParsedSegment[] = [];
  // 匹配 @filepath 格式（路径可以包含 / 和 . 但不能有空格）
  const regex = /@([\w./-]+)/g;
  let lastIndex = 0;
  let match;

  while ((match = regex.exec(text)) !== null) {
    // 添加前面的普通文本
    if (match.index > lastIndex) {
      segments.push({
        type: 'text',
        content: text.slice(lastIndex, match.index),
      });
    }
    // 添加文件提及 (不包含 @ 符号的路径)
    segments.push({
      type: 'file',
      content: match[1],
    });
    lastIndex = regex.lastIndex;
  }

  // 添加剩余的文本
  if (lastIndex < text.length) {
    segments.push({
      type: 'text',
      content: text.slice(lastIndex),
    });
  }

  return segments;
}

/**
 * 渲染带有文件提及高亮的文本
 */
interface FileMentionTextProps {
  text: string;
  className?: string;
}

export function FileMentionText({ text, className }: FileMentionTextProps) {
  const segments = parseFileMentions(text);

  if (segments.length === 0) {
    return <span className={className}>{text}</span>;
  }

  return (
    <span className={cn('whitespace-pre-wrap break-words', className)}>
      {segments.map((segment, index) =>
        segment.type === 'file' ? (
          <FileMentionTag key={index} path={segment.content} size="sm" className="mx-0.5" />
        ) : (
          <span key={index}>{segment.content}</span>
        )
      )}
    </span>
  );
}
