/**
 * ContextMemoryDisplay Component
 * Visualize conversation context and summarization
 * OQI-007: LLM Strategy Agent
 */

import React, { useState, useMemo } from 'react';
import {
  CircleStackIcon,
  DocumentTextIcon,
  ClockIcon,
  ChevronDownIcon,
  ChevronUpIcon,
  TrashIcon,
  BookmarkIcon,
  ArrowDownTrayIcon,
  InformationCircleIcon,
  ExclamationTriangleIcon,
} from '@heroicons/react/24/outline';

// ============================================================================
// Types
// ============================================================================

export interface ContextMessage {
  id: string;
  role: 'user' | 'assistant';
  preview: string;
  timestamp: string;
  tokenCount: number;
  isSummarized?: boolean;
}

export interface ContextSummary {
  id: string;
  createdAt: string;
  messageCount: number;
  content: string;
  tokenCount: number;
}

export interface ContextMemoryState {
  messages: ContextMessage[];
  summaries: ContextSummary[];
  maxContextTokens: number;
  currentTokens: number;
  lastCheckpoint?: string;
}

interface ContextMemoryDisplayProps {
  state: ContextMemoryState;
  onClearOldContext?: () => void;
  onSaveCheckpoint?: () => void;
  onExportConversation?: () => void;
  onRestoreCheckpoint?: (checkpointId: string) => void;
  compact?: boolean;
}

// ============================================================================
// Helper Functions
// ============================================================================

const formatTimestamp = (timestamp: string) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  if (diff < 60000) return 'Just now';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
  return date.toLocaleDateString();
};

const formatTokens = (tokens: number) => {
  if (tokens >= 1000000) return `${(tokens / 1000000).toFixed(1)}M`;
  if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}K`;
  return tokens.toString();
};

// ============================================================================
// Component
// ============================================================================

export const ContextMemoryDisplay: React.FC<ContextMemoryDisplayProps> = ({
  state,
  onClearOldContext,
  onSaveCheckpoint,
  onExportConversation,
  onRestoreCheckpoint,
  compact = false,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [showSummaryContent, setShowSummaryContent] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'messages' | 'summaries'>('messages');

  const usagePercent = useMemo(() => {
    return Math.min((state.currentTokens / state.maxContextTokens) * 100, 100);
  }, [state.currentTokens, state.maxContextTokens]);

  const usageColor = useMemo(() => {
    if (usagePercent >= 90) return 'bg-red-500';
    if (usagePercent >= 70) return 'bg-yellow-500';
    return 'bg-emerald-500';
  }, [usagePercent]);

  const recentMessages = state.messages.filter((m) => !m.isSummarized);
  const summarizedMessages = state.messages.filter((m) => m.isSummarized);

  if (compact) {
    return (
      <div className="p-3 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center gap-2">
            <CircleStackIcon className="w-4 h-4 text-gray-400" />
            <span className="text-sm text-gray-600 dark:text-gray-400">Context</span>
          </div>
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            {isExpanded ? (
              <ChevronUpIcon className="w-4 h-4" />
            ) : (
              <ChevronDownIcon className="w-4 h-4" />
            )}
          </button>
        </div>

        {/* Progress Bar */}
        <div className="h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
          <div
            className={`h-full ${usageColor} transition-all`}
            style={{ width: `${usagePercent}%` }}
          />
        </div>
        <div className="flex justify-between text-xs text-gray-500 mt-1">
          <span>{formatTokens(state.currentTokens)} tokens</span>
          <span>{usagePercent.toFixed(0)}%</span>
        </div>

        {isExpanded && (
          <div className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700 space-y-2">
            <div className="text-xs text-gray-500">
              {recentMessages.length} messages in context
              {state.summaries.length > 0 && ` + ${state.summaries.length} summaries`}
            </div>
            <div className="flex gap-2">
              {onClearOldContext && (
                <button
                  onClick={onClearOldContext}
                  className="flex-1 px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded hover:bg-gray-200 dark:hover:bg-gray-600"
                >
                  Clear Old
                </button>
              )}
              {onSaveCheckpoint && (
                <button
                  onClick={onSaveCheckpoint}
                  className="flex-1 px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded hover:bg-gray-200 dark:hover:bg-gray-600"
                >
                  Checkpoint
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <CircleStackIcon className="w-5 h-5 text-primary-500" />
            <h3 className="font-semibold text-gray-900 dark:text-white">Context Memory</h3>
          </div>
          <div className="flex items-center gap-2">
            {onExportConversation && (
              <button
                onClick={onExportConversation}
                className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg"
                title="Export conversation"
              >
                <ArrowDownTrayIcon className="w-4 h-4" />
              </button>
            )}
            {onSaveCheckpoint && (
              <button
                onClick={onSaveCheckpoint}
                className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg"
                title="Save checkpoint"
              >
                <BookmarkIcon className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>

        {/* Usage Gauge */}
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-600 dark:text-gray-400">Context Usage</span>
            <span className="font-medium text-gray-900 dark:text-white">
              {formatTokens(state.currentTokens)} / {formatTokens(state.maxContextTokens)}
            </span>
          </div>
          <div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
            <div
              className={`h-full ${usageColor} transition-all duration-300`}
              style={{ width: `${usagePercent}%` }}
            />
          </div>
          {usagePercent >= 80 && (
            <div className="flex items-center gap-1 text-xs text-yellow-600 dark:text-yellow-400">
              <ExclamationTriangleIcon className="w-3.5 h-3.5" />
              <span>Context filling up. Old messages may be summarized.</span>
            </div>
          )}
        </div>

        {/* Stats */}
        <div className="grid grid-cols-3 gap-3 mt-3">
          <div className="text-center p-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
            <div className="text-lg font-bold text-gray-900 dark:text-white">{recentMessages.length}</div>
            <div className="text-xs text-gray-500">Active Messages</div>
          </div>
          <div className="text-center p-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
            <div className="text-lg font-bold text-gray-900 dark:text-white">{state.summaries.length}</div>
            <div className="text-xs text-gray-500">Summaries</div>
          </div>
          <div className="text-center p-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
            <div className="text-lg font-bold text-gray-900 dark:text-white">{summarizedMessages.length}</div>
            <div className="text-xs text-gray-500">Summarized</div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setActiveTab('messages')}
          className={`flex-1 py-2 text-sm font-medium border-b-2 transition-colors ${
            activeTab === 'messages'
              ? 'border-primary-500 text-primary-500'
              : 'border-transparent text-gray-500'
          }`}
        >
          Messages ({recentMessages.length})
        </button>
        <button
          onClick={() => setActiveTab('summaries')}
          className={`flex-1 py-2 text-sm font-medium border-b-2 transition-colors ${
            activeTab === 'summaries'
              ? 'border-primary-500 text-primary-500'
              : 'border-transparent text-gray-500'
          }`}
        >
          Summaries ({state.summaries.length})
        </button>
      </div>

      {/* Content */}
      <div className="max-h-64 overflow-y-auto">
        {activeTab === 'messages' && (
          <div className="p-2 space-y-1">
            {recentMessages.length === 0 ? (
              <div className="text-center py-6 text-gray-500 text-sm">
                No messages in context yet
              </div>
            ) : (
              recentMessages.map((message) => (
                <div
                  key={message.id}
                  className="flex items-start gap-2 p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800"
                >
                  <div
                    className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium ${
                      message.role === 'user'
                        ? 'bg-blue-500/20 text-blue-400'
                        : 'bg-purple-500/20 text-purple-400'
                    }`}
                  >
                    {message.role === 'user' ? 'U' : 'A'}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-gray-700 dark:text-gray-300 truncate">
                      {message.preview}
                    </p>
                    <div className="flex items-center gap-2 text-xs text-gray-500 mt-0.5">
                      <span>{formatTimestamp(message.timestamp)}</span>
                      <span>•</span>
                      <span>{message.tokenCount} tokens</span>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        )}

        {activeTab === 'summaries' && (
          <div className="p-2 space-y-2">
            {state.summaries.length === 0 ? (
              <div className="text-center py-6 text-gray-500 text-sm">
                No summaries created yet
              </div>
            ) : (
              state.summaries.map((summary) => (
                <div
                  key={summary.id}
                  className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg"
                >
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <DocumentTextIcon className="w-4 h-4 text-gray-400" />
                      <span className="text-sm font-medium text-gray-900 dark:text-white">
                        {summary.messageCount} messages summarized
                      </span>
                    </div>
                    <button
                      onClick={() =>
                        setShowSummaryContent(
                          showSummaryContent === summary.id ? null : summary.id
                        )
                      }
                      className="text-xs text-primary-500 hover:text-primary-600"
                    >
                      {showSummaryContent === summary.id ? 'Hide' : 'Show'}
                    </button>
                  </div>
                  <div className="flex items-center gap-2 text-xs text-gray-500">
                    <ClockIcon className="w-3.5 h-3.5" />
                    <span>{formatTimestamp(summary.createdAt)}</span>
                    <span>•</span>
                    <span>{summary.tokenCount} tokens</span>
                  </div>
                  {showSummaryContent === summary.id && (
                    <div className="mt-2 p-2 bg-white dark:bg-gray-900 rounded text-sm text-gray-600 dark:text-gray-400">
                      {summary.content}
                    </div>
                  )}
                </div>
              ))
            )}
          </div>
        )}
      </div>

      {/* Footer Actions */}
      <div className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
        <div className="flex items-center gap-2">
          {onClearOldContext && (
            <button
              onClick={onClearOldContext}
              className="flex-1 flex items-center justify-center gap-1 px-3 py-2 text-sm text-red-600 hover:bg-red-50 dark:hover:bg-red-500/10 rounded-lg transition-colors"
            >
              <TrashIcon className="w-4 h-4" />
              Clear Old Context
            </button>
          )}
          {onSaveCheckpoint && (
            <button
              onClick={onSaveCheckpoint}
              className="flex-1 flex items-center justify-center gap-1 px-3 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              <BookmarkIcon className="w-4 h-4" />
              Save Checkpoint
            </button>
          )}
        </div>

        {/* Info */}
        <div className="mt-3 p-2 bg-blue-50 dark:bg-blue-500/10 rounded-lg">
          <div className="flex items-start gap-2">
            <InformationCircleIcon className="w-4 h-4 text-blue-500 mt-0.5" />
            <p className="text-xs text-blue-700 dark:text-blue-300">
              Recent messages are sent in full. Older messages are summarized to save tokens.
              The AI uses summaries to maintain conversation context.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ContextMemoryDisplay;
