import React, { useEffect, useRef, useState } from "react";
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import './ChatWindow.css';
import { FaRegCopy, FaCopy, FaVolumeUp, FaPlay, FaPause, FaDownload, FaSyncAlt } from 'react-icons/fa'; // Import the icons

// Individual message component
const ChatMessage = ({ message, index, onSynthesize, featureName = "default", activePlayingId, onPlayStateChange, evaluationMetadata }) => {
  const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
  const [audioUrl, setAudioUrl] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const audioRef = useRef(null);
  const isVoiceChat = featureName === "voice_chat";

  // Unique ID for this message's audio
  const currentMsgId = message.id || `msg-${index}`;

  useEffect(() => {
    if (message.audioBlob) {
      const url = URL.createObjectURL(message.audioBlob);
      setAudioUrl(url);
      return () => URL.revokeObjectURL(url);
    }
  }, [message.audioBlob]);

  // Removed auto-expand behavior to keep UI clean during long orchestration tasks.
  // The user can manually expand the trace if they wish to see inner-turn details.

  // Handle exclusive playback: stop if someone else starts playing
  useEffect(() => {
    if (activePlayingId && activePlayingId !== currentMsgId && isPlaying) {
      if (audioRef.current) {
        audioRef.current.pause();
        setIsPlaying(false);
      }
    }
  }, [activePlayingId, currentMsgId, isPlaying]);

  // Stop audio on unmount
  useEffect(() => {
    return () => {
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current.src = ""; // Clear source to ensure it stops immediately
      }
    };
  }, []);

  const handlePlayPause = () => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.pause();
        onPlayStateChange(null);
      } else {
        audioRef.current.play();
        onPlayStateChange(currentMsgId);
      }
      setIsPlaying(!isPlaying);
    }
  };

  const handleDownload = () => {
    if (audioUrl) {
      const a = document.createElement("a");
      a.href = audioUrl;
      a.download = `voice_chat_${Date.now()}.wav`;
      a.click();
    }
  };

  const handleReplay = () => {
    if (audioRef.current) {
      audioRef.current.currentTime = 0;
      audioRef.current.play();
      setIsPlaying(true);
      onPlayStateChange(currentMsgId);
    }
  };

  const toggleReasoning = () => {
    setIsReasoningExpanded(!isReasoningExpanded);
  };

  // Function to copy text to clipboard
  const handleCopy = async () => {
    if (message.text) {
      try {
        await navigator.clipboard.writeText(message.text);
        // Optional: Add a state or a toast notification to show "Copied!"
      } catch (err) {
        console.error('Failed to copy text: ', err);
      }
    }
  };
  const isIntermediate = !message.isUser && message.status && !message.status.toLowerCase().includes("finished") && !message.status.toLowerCase().includes("complete");
  
  const assistantMessageClasses = `p-4 shadow-lg max-w-[95%] assistant-message mr-auto text-gray-900 dark:text-gray-100 ${isIntermediate ? 'is-intermediate' : ''}`;
  const userMessageClasses = `max-w-[90%] p-4 shadow-md ml-auto user-message-container`;

  const formatTime = (iso) => {
    if (!iso) return '';
    try {
      return new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } catch { return ''; }
  };

  // Hide "ghost" messages that are neither users nor have any text/reasoning yet.
  // This happens during the very early 'Starting' phase on the backend correctly.
  if (!message.isUser && !message.text && !message.reasoning && message.status !== "Thinking") {
    return null;
  }

  // Use per-message metadata if available; for the latest assistant message, fallback to session-wide 'latest' metadata
  const effectiveEval = message.message_metadata?.evaluation || evaluationMetadata;

  return (
    <div className={message.isUser ? userMessageClasses : assistantMessageClasses}>
      {/* Status indicator moved to top/bottom for better visibility */}
      {(message.reasoning || (message.status === "Thinking")) && (
        <div className="mb-3">
          <button
            onClick={toggleReasoning}
            className="text-xs font-bold text-indigo-600 dark:text-indigo-400 hover:opacity-80 focus:outline-none flex items-center gap-2 px-2 py-1 rounded-md hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors"
          >
            <span className="text-[10px] transform transition-transform duration-200" style={{ transform: isReasoningExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }}>▶</span>
            {message.status && message.status.startsWith("Thought for") ? message.status.toUpperCase() : "THOUGHT TRACE"}
            {message.reasoning && (() => {
              const count = (message.reasoning.match(/Sub-Agent \[/g) || []).length;
              return count > 0 ? (
                <span className="ml-1 px-1.5 py-0.5 text-[9px] bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 rounded-full font-semibold">
                  {count} steps
                </span>
              ) : null;
            })()}
          </button>

          <div
            className={`mt-2 text-xs transition-all duration-500 ease-in-out overflow-y-auto thought-panel pl-4 pr-2 py-1 custom-scrollbar ${isReasoningExpanded ? "max-h-[400px] opacity-100 mb-2" : "max-h-0 opacity-0"
              } text-gray-600 dark:text-gray-400 font-light leading-relaxed markdown-preview max-w-none`}
          >
            <ReactMarkdown remarkPlugins={[remarkGfm]}>{message.reasoning}</ReactMarkdown>
          </div>
        </div>
      )}


      <div className={`markdown-preview max-w-none text-sm leading-relaxed mb-2 ${message.isUser ? 'text-white' : 'text-gray-900 dark:text-gray-100'}`}>
        <ReactMarkdown remarkPlugins={[remarkGfm]}>{message.text}</ReactMarkdown>
      </div>

      {/* Per-Answer Evaluation Metadata (Area 4: Quality Rubric / Feedback / History) */}
      {!message.isUser && effectiveEval && (effectiveEval.rubric || effectiveEval.feedback || (effectiveEval.history && effectiveEval.history.length > 0)) && (
        <div className="mt-4 pt-4 border-t border-gray-100 dark:border-gray-800 animate-in fade-in slide-in-from-top-2 duration-500">
           <details className="group/eval">
              <summary className="flex items-center cursor-pointer list-none text-[10px] font-black uppercase tracking-widest text-indigo-500 hover:text-indigo-600 dark:hover:text-indigo-400 transition-colors">
                 <div className="flex items-center gap-2">
                    <span className="group-open/eval:rotate-90 transition-transform">▶</span>
                    📜 View Quality Audit & Evaluation
                 </div>
              </summary>
              
              <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                 {/* Rubric snippet */}
                 {effectiveEval.rubric && (
                   <div className="flex flex-col p-4 rounded-xl bg-gray-50 dark:bg-black/40 border border-gray-100 dark:border-gray-800 shadow-sm">
                      <div className="text-[10px] font-black text-gray-400 uppercase mb-3 flex items-center gap-2">
                         <div className="w-1.5 h-1.5 bg-gray-300 dark:bg-gray-700 rounded-full"></div> 📝 Quality Rubric
                      </div>
                      <div className="text-xs text-gray-700 dark:text-gray-300 overflow-y-auto max-h-64 custom-scrollbar pr-1 leading-relaxed">
                         <ReactMarkdown remarkPlugins={[remarkGfm]}>{effectiveEval.rubric}</ReactMarkdown>
                      </div>
                   </div>
                 )}
                 
                 {/* Feedback snippet */}
                 {effectiveEval.feedback && (
                   <div className="flex flex-col p-4 rounded-xl bg-indigo-50/40 dark:bg-indigo-500/5 border border-indigo-100/50 dark:border-indigo-500/10 shadow-sm">
                      <div className="text-[10px] font-black text-indigo-500 uppercase mb-3 flex items-center gap-2">
                         <div className="w-1.5 h-1.5 bg-indigo-500 rounded-full animate-pulse"></div> 🤖 Co-Worker Feedback
                      </div>
                      <div className="text-xs text-indigo-900/80 dark:text-indigo-200/70 overflow-y-auto max-h-64 custom-scrollbar pr-1 leading-relaxed">
                         <ReactMarkdown remarkPlugins={[remarkGfm]}>{effectiveEval.feedback}</ReactMarkdown>
                      </div>
                   </div>
                 )}
              </div>

              {/* History Timeline snippet */}
              {effectiveEval.history && effectiveEval.history.length > 0 && (
                <div className="mt-4 p-4 rounded-xl bg-emerald-50/20 dark:bg-emerald-500/5 border border-emerald-100/30 dark:border-emerald-500/10 shadow-sm">
                   <div className="text-[10px] font-black text-emerald-500 uppercase mb-3 flex items-center gap-2">
                      <div className="w-1.5 h-1.5 bg-emerald-500 rounded-full"></div> 🕒 Rework History Timeline
                   </div>
                   <div className="flex flex-col gap-3 max-h-64 overflow-y-auto pr-2 custom-scrollbar">
                      {effectiveEval.history.map((h, i) => (
                        <div key={i} className="flex justify-between items-start text-xs border-l-2 border-emerald-500/20 pl-3 py-1 last:pb-0 transition-all hover:bg-emerald-500/5 rounded-r">
                           <div className="flex flex-col gap-0.5">
                              <span className="font-bold text-gray-800 dark:text-gray-200">
                                {h.type === 'attempt' ? `Attempt ${h.round}` : h.name}
                                {h.score !== undefined && <span className="ml-3 px-1.5 py-0.5 bg-emerald-500 text-white dark:text-emerald-100 rounded-md text-[10px] font-bold shadow-sm">Score: {h.score}%</span>}
                              </span>
                              <span className="text-gray-500 dark:text-gray-400 italic text-[11px] leading-snug">{h.reason || h.message || h.details}</span>
                           </div>
                           <span className="text-gray-400 dark:text-gray-600 font-mono text-[10px]">
                              {h.timestamp ? new Date(h.timestamp * (h.timestamp < 2000000000 ? 1000 : 1)).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : 'Recent'}
                           </span>
                        </div>
                      ))}
                   </div>
                </div>
              )}
           </details>
        </div>
      )}

      {!message.isUser && message.status && (() => {
        const isTerminal = typeof message.status === 'string' && (message.status.toLowerCase().includes("complete") || message.status.toLowerCase().includes("finished"));
        return (
          <div className="mt-2 pt-2 border-t border-gray-100 dark:border-gray-800 transition-all duration-300">
            <div className={`status-chip text-[10px] sm:text-xs font-semibold italic flex items-center gap-2 py-1 px-3 rounded-full border ${
              isTerminal 
                ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-600 dark:text-emerald-400" 
                : "bg-indigo-500/10 border-indigo-500/20 text-indigo-600 dark:text-indigo-300"
            }`}>
              <div className={`w-2 h-2 rounded-full ${
                isTerminal ? "bg-emerald-500" : "bg-indigo-500 animate-pulse"
              }`}></div>
              <span>
                {message.status}
              </span>
            </div>
          </div>
        );
      })()}

      {(message.isPureAnswer || !message.isUser) && (
        <div className="justify-end items-center mt-2 group-audio-container">
          {/* Horizontal line - only for voice chat to separate from voice controls */}
          {isVoiceChat && (
            <div className="border-b border-gray-400 dark:border-gray-600 opacity-20 my-1.5"></div>
          )}
          <div className="flex justify-end items-center gap-1">

            {/* Audio Controls - strictly limited to voice chat feature */}
            {isVoiceChat && (message.audioBlob ? (
              <div className="flex items-center gap-1 mr-auto text-gray-500 dark:text-gray-400">
                <audio
                  ref={audioRef}
                  src={audioUrl}
                  onEnded={() => setIsPlaying(false)}
                  onPlay={() => setIsPlaying(true)}
                  onPause={() => setIsPlaying(false)}
                  className="hidden"
                />
                <button
                  onClick={handlePlayPause}
                  className="p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded transition-colors"
                  title={isPlaying ? "Pause" : "Play"}
                >
                  {isPlaying ? <FaPause size={14} /> : <FaPlay size={14} />}
                </button>
                <button
                  onClick={handleReplay}
                  className="p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded transition-colors"
                  title="Replay"
                >
                  <FaSyncAlt size={14} />
                </button>
                <button
                  onClick={handleDownload}
                  className="p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded transition-colors"
                  title="Download"
                >
                  <FaDownload size={14} />
                </button>
                <div className="h-3 w-px bg-gray-400 dark:bg-gray-600 mx-1 opacity-30"></div>
                <FaVolumeUp size={14} className="opacity-60" />
              </div>
            ) : (!message.isUser && (message.isFromHistory || (message.audioProgress && message.audioProgress > 0)) && (
              <div className="mr-auto flex items-center gap-2 text-[10px] text-gray-500 italic">
                {message.isFromHistory && !message.audioProgress ? (
                  <button
                    onClick={() => onSynthesize(index, message.text)}
                    className="flex items-center gap-1.5 px-2 py-0.5 bg-gray-300 dark:bg-gray-700 hover:bg-indigo-100 dark:hover:bg-indigo-900/30 rounded text-gray-600 dark:text-gray-400 hover:text-indigo-600 transition-colors not-italic font-medium"
                  >
                    <FaVolumeUp size={10} />
                    Synthesize Audio
                  </button>
                ) : (message.audioProgress && (
                  <>
                    <div className="w-2 h-2 bg-indigo-500 rounded-full animate-pulse"></div>
                    Audio generating {message.audioProgress || 0}%...
                  </>
                ))}
              </div>
            )))}

            {/* Timestamp */}
            <span className={`text-[10px] opacity-40 font-medium ${message.isUser ? 'text-white' : 'text-gray-500'}`}>
              {formatTime(message.timestamp)}
            </span>

            {/* Copy Icon - positioned above the bottom line */}
            <button
              onClick={handleCopy}
              className="relative p-2 rounded-right-2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors z-10 group"
              aria-label="Copy message text"
            >
              {/* Outline icon */}
              <FaRegCopy size={16} className="transition-opacity opacity-100 group-hover:opacity-0 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2" />

              {/* Solid icon (initially hidden) */}
              <FaCopy size={16} className="transition-opacity opacity-0 group-hover:opacity-100 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

// Main ChatWindow component with dynamic height calculation
const ChatWindow = ({ messages, chatHistory, maxHeight, onSynthesize, featureName, isStreamingPlaying, onAudioPlay, autoCollapse = false, evaluationMetadata }) => {
  const history = chatHistory || messages || [];

  const containerRef = useRef(null);
  const [activePlayingId, setActivePlayingId] = useState(null);
  const [expandedIndices, setExpandedIndices] = useState({});

  useEffect(() => {
    // If a new stream starts playing, stop any ongoing historical audio
    if (isStreamingPlaying) {
      setActivePlayingId(null);
    }
  }, [isStreamingPlaying]);

  // Better auto-scroll logic using an anchor ref to detect bottom intersection
  const isAtBottomRef = useRef(true);

  // Sync scroll on initial mount or session change
  useEffect(() => {
    if (containerRef.current) {
        containerRef.current.scrollTop = containerRef.current.scrollHeight;
    }
  }, []);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = () => {
      const threshold = 150;
      const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
      isAtBottomRef.current = distanceFromBottom < threshold;
    };

    container.addEventListener('scroll', handleScroll, { passive: true });
    return () => container.removeEventListener('scroll', handleScroll);
  }, []);

  // Use a second effect strictly for responding to content changes
  useEffect(() => {
    if (isAtBottomRef.current && containerRef.current) {
        // Use a slight delay to ensure DOM has rendered the new content/tokens
        requestAnimationFrame(() => {
             if (containerRef.current) {
                containerRef.current.scrollTop = containerRef.current.scrollHeight;
             }
        });
    }
  }, [history, evaluationMetadata]);

  return (
    <div
      ref={containerRef}
      style={{ maxHeight: maxHeight, overflowY: 'auto' }}
      className="px-4 md:px-6 pt-6 pb-32 space-y-6 bg-transparent chat-history-container min-h-full"
    >
      {(() => {
        const lastAssistantIndex = history.slice().reverse().findIndex(m => m.sender === 'assistant' || m.sender === 'assistant'); // Logic for assistant
        const actualLastAssistantIndex = lastAssistantIndex !== -1 ? history.length - 1 - lastAssistantIndex : -1;

        return history.map((message, index) => {
          const isLastMessage = index === history.length - 1;
          const isLastAssistantMessage = index === actualLastAssistantIndex;
          const isSystemLog = message.sender === "system" && (message.text?.includes("Co-Worker") || message.text?.includes("Attempt"));
          const shouldCollapse = (autoCollapse && !isLastMessage && !message.isUser && !expandedIndices[index]) || (isSystemLog && !expandedIndices[index]);

          return (
            <div
              key={index}
              className={`flex ${message.isUser ? "justify-end" : "justify-start"} w-full group relative`}
            >
              {shouldCollapse ? (
                <button
                  onClick={() => setExpandedIndices(prev => ({ ...prev, [index]: true }))}
                  className={`w-full py-2 px-4 mb-2 bg-gray-50 dark:bg-gray-800/50 border border-dashed rounded-xl text-[10px] font-bold transition-all flex items-center justify-center gap-2 ${isSystemLog ? 'border-amber-200 dark:border-amber-900/40 text-amber-500/70 hover:text-amber-600' : 'border-gray-200 dark:border-gray-700 text-gray-400 hover:text-indigo-500'}`}
                >
                  <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                  {isSystemLog ? `INTERNAL LOG: ${message.text?.substring(0, 40).toUpperCase()}... (CLICK TO SEE)` : 'PREVIOUS AI RESPONSE COLLAPSED (CLICK TO EXPAND)'}
                </button>
              ) : (
                <div className="w-full relative">
                  <div className={`flex ${message.isUser ? "justify-end" : "justify-start"}`}>
                    <ChatMessage
                      message={message}
                      index={index}
                      onSynthesize={onSynthesize}
                      featureName={featureName}
                      activePlayingId={activePlayingId}
                      onPlayStateChange={(id) => {
                        setActivePlayingId(id);
                        if (id && onAudioPlay) {
                          onAudioPlay(); // Notify parent to stop streaming (to prevent overlap)
                        }
                      }}
                      evaluationMetadata={isLastAssistantMessage ? evaluationMetadata : null}
                    />
                  </div>
                  {autoCollapse && !isLastMessage && !message.isUser && expandedIndices[index] && (
                    <button
                      onClick={() => setExpandedIndices(prev => {
                        const newState = { ...prev };
                        delete newState[index];
                        return newState;
                      })}
                      className="absolute -bottom-2 left-4 px-2 py-0.5 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md text-[9px] font-bold text-gray-400 hover:text-indigo-500 shadow-sm z-10"
                    >
                      Collapse
                    </button>
                  )}
                </div>
              )}
            </div>
          );
        })
      })()}
    </div>
  );
};

export default ChatWindow;
