/**
 * MemoryManager Component
 * Enhanced memory management with conversation history, archiving, and visualization
 * OQI-007: LLM Strategy Agent - SUBTASK-008
 */

import React, { useState, useMemo, useCallback } from 'react';
import {
  CircleStackIcon,
  ArchiveBoxIcon,
  TrashIcon,
  ArrowDownTrayIcon,
  ClockIcon,
  FolderIcon,
  DocumentTextIcon,
  ChevronRightIcon,
  MagnifyingGlassIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  XMarkIcon,
  ArrowPathIcon,
} from '@heroicons/react/24/outline';

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

export interface ConversationRecord {
  id: string;
  title: string;
  preview: string;
  messageCount: number;
  tokenCount: number;
  createdAt: string;
  updatedAt: string;
  archived: boolean;
  tags?: string[];
}

export interface MemoryUsage {
  totalTokens: number;
  maxTokens: number;
  activeConversations: number;
  archivedConversations: number;
  totalStorageKB: number;
}

export interface ContextWindow {
  used: number;
  max: number;
  reserved: number;
  systemPrompt: number;
  conversationHistory: number;
  tools: number;
}

interface MemoryManagerProps {
  conversations: ConversationRecord[];
  memoryUsage: MemoryUsage;
  contextWindow: ContextWindow;
  onClearConversation?: (id: string) => void;
  onArchiveConversation?: (id: string) => void;
  onRestoreConversation?: (id: string) => void;
  onExportConversation?: (id: string) => void;
  onDeleteConversation?: (id: string) => void;
  onClearAllArchived?: () => void;
  onRefreshUsage?: () => void;
  isLoading?: boolean;
}

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

const formatBytes = (kb: number): string => {
  if (kb >= 1024) return `${(kb / 1024).toFixed(1)} MB`;
  return `${kb.toFixed(1)} KB`;
};

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

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

  if (diff < 86400000) {
    return date.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
  }
  if (diff < 604800000) {
    return date.toLocaleDateString('es-ES', { weekday: 'short' });
  }
  return date.toLocaleDateString('es-ES', { month: 'short', day: 'numeric' });
};

// ============================================================================
// Sub-Components
// ============================================================================

interface ContextWindowVisualizationProps {
  contextWindow: ContextWindow;
}

const ContextWindowVisualization: React.FC<ContextWindowVisualizationProps> = ({ contextWindow }) => {
  const segments = [
    { label: 'System Prompt', value: contextWindow.systemPrompt, color: 'bg-purple-500' },
    { label: 'Conversation', value: contextWindow.conversationHistory, color: 'bg-blue-500' },
    { label: 'Tools', value: contextWindow.tools, color: 'bg-emerald-500' },
    { label: 'Reserved', value: contextWindow.reserved, color: 'bg-gray-400' },
  ];

  const available = contextWindow.max - contextWindow.used;
  const usagePercent = (contextWindow.used / contextWindow.max) * 100;

  return (
    <div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
      <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3">Context Window</h4>

      {/* Progress Bar */}
      <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden flex">
        {segments.map((segment, i) => (
          <div
            key={segment.label}
            className={`${segment.color} transition-all`}
            style={{ width: `${(segment.value / contextWindow.max) * 100}%` }}
            title={`${segment.label}: ${formatTokens(segment.value)}`}
          />
        ))}
      </div>

      {/* Legend */}
      <div className="mt-3 grid grid-cols-2 gap-2">
        {segments.map((segment) => (
          <div key={segment.label} className="flex items-center gap-2 text-xs">
            <div className={`w-3 h-3 rounded ${segment.color}`} />
            <span className="text-gray-600 dark:text-gray-400">{segment.label}</span>
            <span className="text-gray-900 dark:text-white font-medium">{formatTokens(segment.value)}</span>
          </div>
        ))}
      </div>

      {/* Summary */}
      <div className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700 flex justify-between text-sm">
        <div>
          <span className="text-gray-500">Used:</span>
          <span className={`ml-1 font-medium ${usagePercent > 80 ? 'text-red-500' : 'text-gray-900 dark:text-white'}`}>
            {formatTokens(contextWindow.used)} ({usagePercent.toFixed(0)}%)
          </span>
        </div>
        <div>
          <span className="text-gray-500">Available:</span>
          <span className="ml-1 font-medium text-emerald-500">{formatTokens(available)}</span>
        </div>
      </div>

      {usagePercent > 80 && (
        <div className="mt-2 p-2 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg flex items-center gap-2 text-xs text-yellow-600 dark:text-yellow-400">
          <ExclamationTriangleIcon className="w-4 h-4" />
          <span>Context window is filling up. Consider archiving old conversations.</span>
        </div>
      )}
    </div>
  );
};

interface ConversationListItemProps {
  conversation: ConversationRecord;
  onArchive?: () => void;
  onRestore?: () => void;
  onExport?: () => void;
  onDelete?: () => void;
}

const ConversationListItem: React.FC<ConversationListItemProps> = ({
  conversation,
  onArchive,
  onRestore,
  onExport,
  onDelete,
}) => {
  const [showActions, setShowActions] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);

  return (
    <div
      className="group p-3 hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg transition-colors"
      onMouseEnter={() => setShowActions(true)}
      onMouseLeave={() => { setShowActions(false); setConfirmDelete(false); }}
    >
      <div className="flex items-start gap-3">
        <div className={`p-2 rounded-lg ${conversation.archived ? 'bg-gray-200 dark:bg-gray-700' : 'bg-blue-100 dark:bg-blue-900/30'}`}>
          {conversation.archived ? (
            <ArchiveBoxIcon className="w-4 h-4 text-gray-500" />
          ) : (
            <DocumentTextIcon className="w-4 h-4 text-blue-500" />
          )}
        </div>

        <div className="flex-1 min-w-0">
          <p className="font-medium text-gray-900 dark:text-white text-sm truncate">
            {conversation.title}
          </p>
          <p className="text-xs text-gray-500 truncate mt-0.5">
            {conversation.preview}
          </p>
          <div className="flex items-center gap-3 mt-1 text-xs text-gray-400">
            <span>{conversation.messageCount} messages</span>
            <span>{formatTokens(conversation.tokenCount)} tokens</span>
            <span>{formatDate(conversation.updatedAt)}</span>
          </div>
          {conversation.tags && conversation.tags.length > 0 && (
            <div className="flex gap-1 mt-1.5">
              {conversation.tags.map((tag) => (
                <span
                  key={tag}
                  className="px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-500 text-xs rounded"
                >
                  {tag}
                </span>
              ))}
            </div>
          )}
        </div>

        {/* Actions */}
        <div className={`flex items-center gap-1 transition-opacity ${showActions ? 'opacity-100' : 'opacity-0'}`}>
          {!confirmDelete ? (
            <>
              {conversation.archived ? (
                onRestore && (
                  <button
                    onClick={onRestore}
                    className="p-1.5 text-gray-400 hover:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-900/20 rounded-lg"
                    title="Restore"
                  >
                    <ArrowPathIcon className="w-4 h-4" />
                  </button>
                )
              ) : (
                onArchive && (
                  <button
                    onClick={onArchive}
                    className="p-1.5 text-gray-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg"
                    title="Archive"
                  >
                    <ArchiveBoxIcon className="w-4 h-4" />
                  </button>
                )
              )}
              {onExport && (
                <button
                  onClick={onExport}
                  className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
                  title="Export"
                >
                  <ArrowDownTrayIcon className="w-4 h-4" />
                </button>
              )}
              {onDelete && (
                <button
                  onClick={() => setConfirmDelete(true)}
                  className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg"
                  title="Delete"
                >
                  <TrashIcon className="w-4 h-4" />
                </button>
              )}
            </>
          ) : (
            <>
              <button
                onClick={onDelete}
                className="px-2 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
              >
                Confirm
              </button>
              <button
                onClick={() => setConfirmDelete(false)}
                className="p-1 text-gray-400 hover:text-gray-600"
              >
                <XMarkIcon className="w-4 h-4" />
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// ============================================================================
// Main Component
// ============================================================================

export const MemoryManager: React.FC<MemoryManagerProps> = ({
  conversations,
  memoryUsage,
  contextWindow,
  onClearConversation,
  onArchiveConversation,
  onRestoreConversation,
  onExportConversation,
  onDeleteConversation,
  onClearAllArchived,
  onRefreshUsage,
  isLoading = false,
}) => {
  const [activeTab, setActiveTab] = useState<'active' | 'archived'>('active');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<'recent' | 'tokens' | 'messages'>('recent');

  const filteredConversations = useMemo(() => {
    let filtered = conversations.filter((c) =>
      activeTab === 'archived' ? c.archived : !c.archived
    );

    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter((c) =>
        c.title.toLowerCase().includes(query) ||
        c.preview.toLowerCase().includes(query) ||
        c.tags?.some((t) => t.toLowerCase().includes(query))
      );
    }

    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'tokens':
          return b.tokenCount - a.tokenCount;
        case 'messages':
          return b.messageCount - a.messageCount;
        default:
          return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
      }
    });

    return filtered;
  }, [conversations, activeTab, searchQuery, sortBy]);

  const activeConversations = conversations.filter((c) => !c.archived);
  const archivedConversations = conversations.filter((c) => c.archived);

  const usagePercent = (memoryUsage.totalTokens / memoryUsage.maxTokens) * 100;

  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-4">
          <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">Memory Manager</h3>
          </div>
          {onRefreshUsage && (
            <button
              onClick={onRefreshUsage}
              disabled={isLoading}
              className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg disabled:opacity-50"
              title="Refresh"
            >
              <ArrowPathIcon className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
            </button>
          )}
        </div>

        {/* Usage Overview */}
        <div className="grid grid-cols-4 gap-3">
          <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              {formatTokens(memoryUsage.totalTokens)}
            </div>
            <div className="text-xs text-gray-500">Total Tokens</div>
          </div>
          <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              {memoryUsage.activeConversations}
            </div>
            <div className="text-xs text-gray-500">Active</div>
          </div>
          <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              {memoryUsage.archivedConversations}
            </div>
            <div className="text-xs text-gray-500">Archived</div>
          </div>
          <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
            <div className="text-xl font-bold text-gray-900 dark:text-white">
              {formatBytes(memoryUsage.totalStorageKB)}
            </div>
            <div className="text-xs text-gray-500">Storage</div>
          </div>
        </div>

        {/* Usage Bar */}
        <div className="mt-3">
          <div className="flex items-center justify-between text-sm mb-1">
            <span className="text-gray-500">Memory Usage</span>
            <span className={`font-medium ${usagePercent > 80 ? 'text-red-500' : 'text-gray-900 dark:text-white'}`}>
              {usagePercent.toFixed(0)}%
            </span>
          </div>
          <div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
            <div
              className={`h-full transition-all ${
                usagePercent > 80 ? 'bg-red-500' : usagePercent > 60 ? 'bg-yellow-500' : 'bg-emerald-500'
              }`}
              style={{ width: `${usagePercent}%` }}
            />
          </div>
        </div>
      </div>

      {/* Context Window Visualization */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <ContextWindowVisualization contextWindow={contextWindow} />
      </div>

      {/* Tabs */}
      <div className="flex border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setActiveTab('active')}
          className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium border-b-2 transition-colors ${
            activeTab === 'active'
              ? 'border-primary-500 text-primary-500'
              : 'border-transparent text-gray-500'
          }`}
        >
          <FolderIcon className="w-4 h-4" />
          Active ({activeConversations.length})
        </button>
        <button
          onClick={() => setActiveTab('archived')}
          className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium border-b-2 transition-colors ${
            activeTab === 'archived'
              ? 'border-primary-500 text-primary-500'
              : 'border-transparent text-gray-500'
          }`}
        >
          <ArchiveBoxIcon className="w-4 h-4" />
          Archived ({archivedConversations.length})
        </button>
      </div>

      {/* Search & Sort */}
      <div className="p-3 border-b border-gray-200 dark:border-gray-700 flex items-center gap-3">
        <div className="flex-1 relative">
          <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search conversations..."
            className="w-full pl-9 pr-3 py-2 text-sm bg-gray-100 dark:bg-gray-800 border-0 rounded-lg focus:ring-2 focus:ring-primary-500"
          />
        </div>
        <select
          value={sortBy}
          onChange={(e) => setSortBy(e.target.value as typeof sortBy)}
          className="px-3 py-2 text-sm bg-gray-100 dark:bg-gray-800 border-0 rounded-lg focus:ring-2 focus:ring-primary-500"
        >
          <option value="recent">Most Recent</option>
          <option value="tokens">Most Tokens</option>
          <option value="messages">Most Messages</option>
        </select>
      </div>

      {/* Conversation List */}
      <div className="max-h-80 overflow-y-auto">
        {filteredConversations.length === 0 ? (
          <div className="p-8 text-center">
            <div className="w-12 h-12 mx-auto mb-3 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center">
              {activeTab === 'archived' ? (
                <ArchiveBoxIcon className="w-6 h-6 text-gray-400" />
              ) : (
                <DocumentTextIcon className="w-6 h-6 text-gray-400" />
              )}
            </div>
            <p className="text-gray-500 text-sm">
              {searchQuery
                ? 'No conversations match your search'
                : activeTab === 'archived'
                ? 'No archived conversations'
                : 'No active conversations'}
            </p>
          </div>
        ) : (
          <div className="divide-y divide-gray-100 dark:divide-gray-800">
            {filteredConversations.map((conversation) => (
              <ConversationListItem
                key={conversation.id}
                conversation={conversation}
                onArchive={onArchiveConversation ? () => onArchiveConversation(conversation.id) : undefined}
                onRestore={onRestoreConversation ? () => onRestoreConversation(conversation.id) : undefined}
                onExport={onExportConversation ? () => onExportConversation(conversation.id) : undefined}
                onDelete={onDeleteConversation ? () => onDeleteConversation(conversation.id) : undefined}
              />
            ))}
          </div>
        )}
      </div>

      {/* Footer Actions */}
      {activeTab === 'archived' && archivedConversations.length > 0 && onClearAllArchived && (
        <div className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
          <button
            onClick={onClearAllArchived}
            className="w-full flex items-center justify-center gap-2 px-4 py-2 text-sm text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
          >
            <TrashIcon className="w-4 h-4" />
            Clear All Archived ({archivedConversations.length})
          </button>
        </div>
      )}
    </div>
  );
};

export default MemoryManager;
