import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { User, FileText } from 'lucide-react';
import { Message, ReferenceInfo } from '../contexts/ChatContext';
import PDFViewer from './PDFViewer';
import SimpleMarkdownRenderer from './SimpleMarkdownRenderer';

interface MessageBubbleProps {
  message: Message;
}

interface SourceInfo {
  filename: string;
  pageNumber: number;
  fileId: string;
}

const MessageBubble: React.FC<MessageBubbleProps> = ({ message }) => {
  const isUser = message.isUser;
  const [selectedPage, setSelectedPage] = useState<{fileId: string, filename: string, pageNumber: number} | null>(null);

  // 소스 문자열을 파싱하여 파일명, file_id, 페이지 번호 추출
  const parseSource = (source: string): SourceInfo | null => {
    const match = source.match(/^(.+?)::(.+?)\s*\[p(\d+)\]$/);
    if (match) {
      return {
        filename: match[1],
        fileId: match[2],
        pageNumber: parseInt(match[3])
      };
    }
    return null;
  };

  // 참조 문서를 파일명별로 그룹화
  const groupSourcesByFile = (sources: string[]) => {
    const grouped: { [filename: string]: { fileId: string; pages: number[] } } = {};
    
    sources.forEach(source => {
      const sourceInfo = parseSource(source);
      if (sourceInfo) {
        if (!grouped[sourceInfo.filename]) {
          grouped[sourceInfo.filename] = {
            fileId: sourceInfo.fileId,
            pages: []
          };
        }
        if (!grouped[sourceInfo.filename].pages.includes(sourceInfo.pageNumber)) {
          grouped[sourceInfo.filename].pages.push(sourceInfo.pageNumber);
        }
      }
    });

    // 페이지 번호 정렬
    Object.keys(grouped).forEach(filename => {
      grouped[filename].pages.sort((a, b) => a - b);
    });

    return grouped;
  };

  const handleSourceClick = (source: string) => {
    const sourceInfo = parseSource(source);
    if (!sourceInfo) return;

    // 파싱된 정보를 직접 사용
    setSelectedPage({
      fileId: sourceInfo.fileId,
      filename: sourceInfo.filename,
      pageNumber: sourceInfo.pageNumber
    });
  };

  // 인라인 링크 클릭 핸들러
  const handleInlineReferenceClick = (fileId: string, pageNumber: number, filename: string) => {
    setSelectedPage({
      fileId: fileId,
      filename: filename,
      pageNumber: pageNumber
    });
  };

  return (
    <>
      <div className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-6`}>
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3 }}
          className={`flex items-start space-x-3 ${
            isUser 
              ? 'flex-row-reverse space-x-reverse w-full max-w-none' 
              : 'w-full'
          }`}
          style={isUser ? { maxWidth: '60vw' } : {}}
        >
          {/* 아바타 */}
          <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
            isUser 
              ? 'bg-gradient-to-r from-blue-500 to-purple-500' 
              : 'bg-transparent'
          }`}>
            {isUser ? (
              <User className="w-4 h-4 text-white" />
            ) : (
              <img 
                src="/images/woongtalk_bgremove.png" 
                alt="연구QA 챗봇" 
                className="w-8 h-8"
              />
            )}
          </div>

          {/* 메시지 내용 */}
          <div className={`rounded-2xl px-4 py-3 flex-1 border border-gray-200 ${
            isUser
              ? 'bg-gradient-to-r from-blue-500 to-purple-500 text-white'
              : 'bg-gray-100 text-gray-800'
          }`}>
            {isUser ? (
              <div className="whitespace-pre-wrap break-words">
                {message.content}
              </div>
            ) : (
              <>
                {console.log('🔍 MessageBubble - message.detailedReferences:', message.detailedReferences)}
                {console.log('🔍 MessageBubble - message.detailedReferences 길이:', message.detailedReferences?.length)}
                <SimpleMarkdownRenderer 
                  content={message.content || ''} 
                  detailedReferences={message.detailedReferences}
                  onReferenceClick={handleInlineReferenceClick}
                />
              </>
            )}
            
            {/* 소스 정보 */}
            {!isUser && message.sources && message.sources.length > 0 && (
              <div className="mt-3 pt-3" style={{ 
                borderTop: 'none !important', 
                border: 'none !important',
                borderBottom: 'none !important',
                borderLeft: 'none !important',
                borderRight: 'none !important',
                outline: 'none !important',
                boxShadow: 'none !important'
              }}>
                <div className="flex items-center space-x-1 text-sm opacity-75">
                  <FileText className="w-4 h-4" />
                  <span>참조 문서:</span>
                </div>
                <div className="mt-1 space-y-1">
                  {Object.entries(groupSourcesByFile(message.sources)).map(([filename, fileData], index) => (
                    <div key={index} className="text-sm bg-white/20 rounded px-2 py-1">
                      <div className="flex items-center flex-wrap">
                        <span className="text-[rgb(90,2,200)] font-medium">{filename}</span>
                        <div className="flex items-center ml-2 space-x-1">
                          {fileData.pages.map((pageNumber, pageIndex) => (
                            <button
                              key={pageIndex}
                              onClick={() => {
                                // 해당 파일의 첫 번째 페이지로 PDF 뷰어 열기
                                const source = `${filename}::${fileData.fileId} [p${pageNumber}]`;
                                handleSourceClick(source);
                              }}
                              className="text-blue-500 hover:text-blue-100 underline cursor-pointer transition-colors"
                            >
                              [p{pageNumber}]
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </motion.div>
      </div>

      {/* PDF 뷰어 */}
      {selectedPage && (
        <PDFViewer
          fileId={selectedPage.fileId}
          filename={selectedPage.filename}
          pageNumber={selectedPage.pageNumber}
          onClose={() => setSelectedPage(null)}
        />
      )}
    </>
  );
};

export default MessageBubble;