import React, { useState } from 'react';
import { copyToClipboard } from '../utils/clipboard';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Message, Role } from '../types';
import { Bot, User, AlertCircle, Copy, Check, Search, ChevronDown, ChevronRight } from 'lucide-react';
import { useLanguage } from '../contexts/LanguageContext';
import { ChatSource } from '../types';

interface ChatMessageProps {
  message: Message;
  onPreviewSource?: (source: ChatSource) => void;
  onOpenFile?: (source: ChatSource) => void;
}

const ChatMessage: React.FC<ChatMessageProps> = ({ message, onPreviewSource, onOpenFile }) => {
  const { t } = useLanguage();
  const isUser = message.role === Role.USER;
  const [copied, setCopied] = useState(false);
  const [sourcesExpanded, setSourcesExpanded] = useState(false);

  const handleCopy = async () => {
    const success = await copyToClipboard(message.text);
    if (success) {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const renderContent = (content: string) => {
    return (
      <div className="markdown-body text-sm leading-relaxed">
        <ReactMarkdown
          remarkPlugins={[remarkGfm]}
          components={{
            code({ node, inline, className, children, ...props }: any) {
              const match = /language-(\w+)/.exec(className || '');
              const language = match ? match[1] : '';

              // Check if it's a Mermaid diagram
              if (language === 'mermaid') {
                return (
                  <div className="my-4 p-4 bg-slate-50 border border-slate-200 rounded-lg overflow-x-auto">
                    <pre className="text-xs text-slate-600 font-mono whitespace-pre-wrap">
                      {String(children).replace(/\n$/, '')}
                    </pre>
                    <div className="text-xs text-slate-400 mt-2">
                      💡 Mermaid diagram (rendering requires mermaid.js)
                    </div>
                  </div>
                );
              }

              // Code block with language
              if (!inline && match) {
                return (
                  <div className="my-3">
                    <div className="flex items-center justify-between bg-slate-700 text-slate-200 px-3 py-1 rounded-t text-xs">
                      <span className="font-mono">{language}</span>
                    </div>
                    <pre className="bg-slate-800 text-slate-100 p-3 rounded-b overflow-x-auto">
                      <code className={className} {...props}>
                        {children}
                      </code>
                    </pre>
                  </div>
                );
              }

              // Inline code
              return (
                <code className="bg-slate-100 text-slate-800 rounded px-1.5 py-0.5 text-xs font-mono" {...props}>
                  {children}
                </code>
              );
            },
            // Style headings
            h2: ({ children }) => (
              <h2 className="text-lg font-semibold mt-4 mb-2 text-slate-800">{children}</h2>
            ),
            h3: ({ children }) => (
              <h3 className="text-base font-semibold mt-3 mb-2 text-slate-700">{children}</h3>
            ),
            // Style lists
            ul: ({ children }) => (
              <ul className="list-disc list-inside space-y-1 my-2">{children}</ul>
            ),
            ol: ({ children }) => (
              <ol className="list-decimal list-inside space-y-1 my-2">{children}</ol>
            ),
            // Style paragraphs
            p: ({ children }) => (
              <p className="my-2 leading-relaxed">{children}</p>
            ),
            // Style tables
            table: ({ children }) => (
              <div className="overflow-x-auto my-3">
                <table className="min-w-full border border-slate-200 rounded">{children}</table>
              </div>
            ),
            th: ({ children }) => (
              <th className="border border-slate-200 bg-slate-50 px-3 py-2 text-left text-sm font-semibold">{children}</th>
            ),
            td: ({ children }) => (
              <td className="border border-slate-200 px-3 py-2 text-sm">{children}</td>
            ),
          }}
        >
          {content}
        </ReactMarkdown>
      </div>
    );
  };

  return (
    <div className={`flex w-full ${isUser ? 'justify-end' : 'justify-start'} animate-in fade-in slide-in-from-bottom-2 duration-300`}>
      <div className={`flex max-w-[85%] md:max-w-[75%] gap-3 ${isUser ? 'flex-row-reverse' : 'flex-row'}`}>

        {/* Avatar */}
        <div className={`shrink-0 w-8 h-8 rounded-full flex items-center justify-center shadow-sm ${isUser ? 'bg-blue-600 text-white' : 'bg-white border border-slate-200 text-purple-600'
          }`}>
          {isUser ? <User className="w-5 h-5" /> : <Bot className="w-5 h-5" />}
        </div>

        {/* Message Bubble + Sources */}
        <div className={`flex flex-col ${isUser ? 'items-end' : 'items-start'} group max-w-full`}>
          <div className={`relative px-5 py-3.5 rounded-2xl shadow-sm ${isUser
            ? 'bg-blue-600 text-white rounded-tr-none'
            : message.isError
              ? 'bg-red-50 border border-red-200 text-red-700 rounded-tl-none'
              : 'bg-white border border-slate-200 text-slate-800 rounded-tl-none'
            }`}>
            {message.isError && (
              <div className="flex items-center gap-2 mb-2 text-red-600 font-semibold">
                <AlertCircle className="w-4 h-4" />
                <span>{t('errorLabel')}</span>
              </div>
            )}
            <div className={`${isUser ? 'text-white' : 'text-slate-800'}`}>
              {renderContent(message.text)}
            </div>

            {/* Copy Button (Always visible, icon only) */}
            <div className={`flex justify-end mt-2 pt-2 border-t ${isUser ? 'border-white/20' : 'border-slate-100/50'}`}>
              <button
                onClick={handleCopy}
                className={`flex items-center justify-center p-1.5 rounded transition-colors ${isUser
                  ? 'text-blue-100 hover:bg-blue-700'
                  : 'text-slate-400 hover:bg-slate-100 text-slate-500'
                  }`}
                title={copied ? t('copied') : t('copy')}
              >
                {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
              </button>
            </div>
          </div>

          {/* Timestamp */}
          <span className="text-[10px] text-slate-400 mt-1 px-1">
            {new Date(message.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
          </span>

          {/* Sources (Collapsible) */}
          {!isUser && message.sources && message.sources.length > 0 && (
            <div className="mt-3 w-full border-t border-slate-200 pt-3">
              <button
                onClick={() => setSourcesExpanded(!sourcesExpanded)}
                className="flex items-center gap-2 text-sm text-slate-600 hover:text-slate-800 transition-colors mb-2"
              >
                {sourcesExpanded ? (
                  <ChevronDown className="w-4 h-4" />
                ) : (
                  <ChevronRight className="w-4 h-4" />
                )}
                <Search className="w-4 h-4" />
                <span className="font-medium">{t('citationSources')} ({message.sources.length})</span>
              </button>

              {sourcesExpanded && (
                <div className="grid gap-3 pl-6 animate-in slide-in-from-top-2 duration-200">
                  {message.sources.map((source, index) => (
                    <div
                      key={`${source.fileName}-${source.chunkIndex}-${index}`}
                      className="bg-slate-50 border border-slate-200 rounded-lg p-3 hover:shadow-sm transition-all cursor-pointer hover:border-blue-300 group/source"
                      onClick={() => onPreviewSource?.(source)}
                    >
                      <div className="flex justify-between items-start mb-2">
                        {source.fileId ? (
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              onOpenFile?.(source);
                            }}
                            className="font-medium text-slate-800 text-sm truncate pr-2 hover:text-blue-600 hover:underline text-left pointer-events-auto relative z-10"
                            title={source.fileName}
                          >
                            {source.fileName}
                          </button>
                        ) : (
                          <div className="font-medium text-slate-800 text-sm truncate pr-2" title={source.fileName}>{source.fileName}</div>
                        )}
                        <div className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full shrink-0">
                          {(source.score * 100).toFixed(1)}%
                        </div>
                      </div>
                      <div className="text-slate-600 text-sm leading-relaxed line-clamp-2">
                        {source.content}
                      </div>
                      <div className="text-xs text-slate-400 mt-2 flex justify-between items-center">
                        <span>{t('chunkNumber')} #{source.chunkIndex + 1}</span>
                        <span className="text-blue-500 opacity-0 group-hover/source:opacity-100 transition-opacity flex items-center gap-1">
                          {t('sourcePreview')} &rarr;
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ChatMessage;
