'use client';

import React, { memo, useCallback, useMemo } from 'react';
import { cn } from '@/utils';
import { InputAsset } from '../types/node';

interface InputMentionProps {
  inputText: string;
  inputAssets: InputAsset[];
  onChange: (value: string) => void;
  onAssetSelect?: (asset: InputAsset) => void;
}

function InputMentionComponent({
  inputText,
  inputAssets,
  onChange,
  onAssetSelect,
}: InputMentionProps) {
  // Parse mentions in the input text
  const mentions = useMemo(() => {
    const mentionRegex = /@(\w+)/g;
    const matches: { index: number; name: string }[] = [];
    let match;
    while ((match = mentionRegex.exec(inputText)) !== null) {
      matches.push({ index: match.index, name: match[1] });
    }
    return matches;
  }, [inputText]);

  // Find asset by alias
  const findAssetByAlias = useCallback((alias: string) => {
    return inputAssets.find(asset =>
      asset.alias?.toLowerCase() === alias.toLowerCase() ||
      asset.name?.toLowerCase().includes(alias.toLowerCase())
    );
  }, [inputAssets]);

  // Handle mention click
  const handleMentionClick = useCallback((name: string) => {
    const asset = findAssetByAlias(name);
    if (asset && onAssetSelect) {
      onAssetSelect(asset);
    }
  }, [findAssetByAlias, onAssetSelect]);

  // Render text with highlighted mentions
  const renderTextWithMentions = useCallback(() => {
    if (mentions.length === 0) {
      return <span>{inputText}</span>;
    }

    const parts: React.ReactNode[] = [];
    let lastIndex = 0;

    mentions.forEach((mention, i) => {
      // Add text before mention
      if (mention.index > lastIndex) {
        parts.push(
          <span key={`text-${i}`}>{inputText.slice(lastIndex, mention.index)}</span>
        );
      }

      // Add mention
      const asset = findAssetByAlias(mention.name);
      parts.push(
        <span
          key={`mention-${i}`}
          onClick={() => handleMentionClick(mention.name)}
          className={cn(
            "cursor-pointer transition-colors",
            asset
              ? "text-cyan-400 hover:text-cyan-300"
              : "text-red-400 hover:text-red-300"
          )}
          title={asset ? `引用: ${asset.name}` : '未找到匹配的素材'}
        >
          @{mention.name}
        </span>
      );

      lastIndex = mention.index + mention.name.length + 1; // +1 for @
    });

    // Add remaining text
    if (lastIndex < inputText.length) {
      parts.push(<span key="text-end">{inputText.slice(lastIndex)}</span>);
    }

    return <>{parts}</>;
  }, [inputText, mentions, findAssetByAlias, handleMentionClick]);

  return (
    <div className="relative">
      <div className="text-sm text-foreground/80 whitespace-pre-wrap">
        {renderTextWithMentions()}
      </div>
    </div>
  );
}

export const InputMention = memo(InputMentionComponent);
