import { useState, useEffect, useCallback } from 'react';
import { listMemories, deleteMemory } from '@/api/memory';

interface MemoryEntry {
  id: string;
  user_id: string;
  content: string;
  category: string;
  importance: number;
  session_id?: string;
  created_at: number | string;
}

interface MemoryPanelProps {
  isOpen: boolean;
  onClose: () => void;
}

const CATEGORY_LABELS: Record<string, string> = {
  user_preference: '偏好',
  personal_info: '个人信息',
  conversation: '对话',
  knowledge: '知识',
  event: '事件',
  task: '任务',
  relationship: '关系',
};

const CATEGORY_COLORS: Record<string, string> = {
  user_preference: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
  personal_info: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  conversation: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
  knowledge: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  event: 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400',
  task: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-400',
  relationship: 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400',
};

function formatTime(ts: number | string): string {
  const date = new Date(typeof ts === 'string' ? parseInt(ts, 10) : ts);
  if (isNaN(date.getTime())) return '';
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMin = Math.floor(diffMs / 60000);
  if (diffMin < 1) return '刚刚';
  if (diffMin < 60) return `${diffMin}分钟前`;
  const diffHour = Math.floor(diffMin / 60);
  if (diffHour < 24) return `${diffHour}小时前`;
  const diffDay = Math.floor(diffHour / 24);
  if (diffDay < 7) return `${diffDay}天前`;
  return date.toLocaleDateString('zh-CN');
}

export function MemoryPanel({ isOpen, onClose }: MemoryPanelProps) {
  const [memories, setMemories] = useState<MemoryEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [confirmId, setConfirmId] = useState<string | null>(null);
  const [error, setError] = useState('');

  const fetchMemories = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const resp: any = await listMemories();
      // 后端可能返回 { memories: [...] } 或直接是数组
      const list = Array.isArray(resp) ? resp : (resp.memories || resp.data || []);
      setMemories(list);
    } catch (err) {
      setError('加载记忆失败，请检查记忆服务是否运行');
      console.error('[MemoryPanel] 加载记忆失败:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      fetchMemories();
      setConfirmId(null);
    }
  }, [isOpen, fetchMemories]);

  // ESC 关闭
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen && !confirmId) {
        onClose();
      }
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose, confirmId]);

  const handleDelete = useCallback(async (id: string) => {
    setDeletingId(id);
    setConfirmId(null);
    try {
      await deleteMemory(id);
      setMemories((prev) => prev.filter((m) => m.id !== id));
    } catch (err) {
      console.error('[MemoryPanel] 删除记忆失败:', err);
    } finally {
      setDeletingId(null);
    }
  }, []);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pt-[10vh]">
      {/* 背景遮罩 */}
      <div className="absolute inset-0 bg-black/30 backdrop-blur-sm" onClick={onClose} />

      {/* 面板 */}
      <div className="relative w-full max-w-lg mx-4 bg-white dark:bg-gray-850 rounded-2xl shadow-2xl border border-pink-100 dark:border-pink-800 flex flex-col max-h-[75vh]">
        {/* 标题栏 */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-pink-100 dark:border-pink-800">
          <h2 className="text-base font-semibold text-gray-800 dark:text-gray-200">
            🧠 记忆管理
          </h2>
          <div className="flex items-center gap-2">
            <button
              onClick={fetchMemories}
              disabled={loading}
              className="text-xs px-2 py-1 text-gray-400 hover:text-pink-500 hover:bg-pink-50 dark:hover:bg-pink-900/20 rounded-lg transition-colors"
            >
              {loading ? '刷新中…' : '🔄 刷新'}
            </button>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>

        {/* 内容区域 */}
        <div className="flex-1 overflow-y-auto">
          {loading && memories.length === 0 && (
            <div className="py-12 text-center">
              <div className="h-5 w-5 mx-auto animate-spin rounded-full border-2 border-pink-400 border-t-transparent" />
              <p className="text-sm text-gray-400 mt-3">加载中…</p>
            </div>
          )}
          {error && (
            <div className="py-12 text-center text-sm text-red-400">{error}</div>
          )}
          {!loading && !error && memories.length === 0 && (
            <div className="py-12 text-center text-sm text-gray-400">
              还没有记忆哦，和昔涟多聊聊吧 ♪
            </div>
          )}
          {memories.length > 0 && (
            <>
              <div className="px-4 py-2 text-xs text-gray-400 border-b border-pink-50 dark:border-pink-900">
                共 {memories.length} 条记忆
              </div>
              {memories.map((mem) => {
                const categoryLabel = CATEGORY_LABELS[mem.category] || mem.category || '其他';
                const colorClass = CATEGORY_COLORS[mem.category] || 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400';

                return (
                  <div
                    key={mem.id}
                    className="px-4 py-3 border-b border-pink-50 dark:border-pink-900/50 last:border-b-0 hover:bg-pink-50/50 dark:hover:bg-pink-900/10 transition-colors group"
                  >
                    <div className="flex items-start gap-2">
                      <div className="flex-1 min-w-0">
                        <p className="text-sm text-gray-700 dark:text-gray-200 break-words">
                          {mem.content}
                        </p>
                        <div className="flex items-center gap-2 mt-1.5">
                          <span className={`text-xs px-1.5 py-0.5 rounded-full font-medium ${colorClass}`}>
                            {categoryLabel}
                          </span>
                          <span className="text-xs text-gray-400">
                            重要度 {mem.importance}/10
                          </span>
                          <span className="text-xs text-gray-400">
                            {formatTime(mem.created_at)}
                          </span>
                        </div>
                      </div>

                      {/* 删除按钮 */}
                      <div className="shrink-0">
                        {confirmId === mem.id ? (
                          <div className="flex items-center gap-1">
                            <button
                              onClick={() => handleDelete(mem.id)}
                              disabled={deletingId === mem.id}
                              className="text-xs px-2 py-1 bg-red-400 hover:bg-red-500 text-white rounded-lg transition-colors"
                            >
                              {deletingId === mem.id ? '…' : '确认'}
                            </button>
                            <button
                              onClick={() => setConfirmId(null)}
                              className="text-xs px-2 py-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg transition-colors"
                            >
                              取消
                            </button>
                          </div>
                        ) : (
                          <button
                            onClick={() => setConfirmId(mem.id)}
                            className="opacity-0 group-hover:opacity-100 p-1 text-gray-400 hover:text-red-400 transition-all"
                            title="删除记忆"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                          </button>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </>
          )}
        </div>

        {/* 底部 */}
        <div className="px-4 py-2 border-t border-pink-100 dark:border-pink-800 text-xs text-gray-400 text-center">
          <kbd className="px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-xs">ESC</kbd> 关闭
          {' · '}
          点击垃圾桶图标删除记忆
        </div>
      </div>
    </div>
  );
}
