import { useState, useCallback } from 'react';
import { useSession } from '@/hooks/useSession';
import { useSessionStore } from '@/store/sessionStore';
import { usePageStore } from '@/store/pageStore';
import { CyreneAvatar } from '@/components/persona/CyreneAvatar';
import { exportSession, type ExportFormat } from '@/api/sessions';
import type { Session } from '@/types/session';

interface SidebarProps {
  onClose?: () => void;
  onMemoryClick?: () => void;
}

export function Sidebar({ onClose, onMemoryClick }: SidebarProps) {
  const {
    sessions,
    createSession,
    deleteSession,
    deleteAllSessions,
    clearMainSession,
    setCurrentSession,
    isAdmin,
  } = useSession();
  const currentSessionId = useSessionStore((s) => s.currentSessionId);

  // 确认弹窗状态
  const [confirmAction, setConfirmAction] = useState<{
    type: 'delete' | 'clearMain' | 'deleteAll';
    sessionId?: string;
  } | null>(null);

  // 导出下拉状态
  const [exportMenuId, setExportMenuId] = useState<string | null>(null);
  const [exportingId, setExportingId] = useState<string | null>(null);

  /** 执行导出 */
  const handleExport = useCallback(async (sessionId: string, format: ExportFormat) => {
    setExportMenuId(null);
    setExportingId(sessionId);
    try {
      await exportSession(sessionId, format);
    } catch (err) {
      console.error('[Sidebar] 导出失败:', err);
      alert(err instanceof Error ? err.message : '导出失败');
    } finally {
      setExportingId(null);
    }
  }, []);

  // 按 updated_at 降序排列
  const displaySessions = [...sessions].sort((a, b) => {
    const ta = typeof a.updated_at === 'string' ? parseInt(a.updated_at, 10) : (a.updated_at as unknown as number);
    const tb = typeof b.updated_at === 'string' ? parseInt(b.updated_at, 10) : (b.updated_at as unknown as number);
    return (tb || 0) - (ta || 0);
  });

  const handleNewChat = async () => {
    const session = await createSession();
    if (session && onClose) onClose();
  };

  const handleSelectSession = (id: string) => {
    setCurrentSession(id);
    usePageStore.getState().goToChat();
    if (onClose) onClose();
  };

  const handleMainSession = async () => {
    const mainSession = displaySessions.find((s) => s.is_main);
    if (mainSession) {
      setCurrentSession(mainSession.id);
      usePageStore.getState().goToChat();
      if (onClose) onClose();
    }
  };

  const handleDeleteClick = (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
    const session = displaySessions.find((s) => s.id === id);
    // 管理员主对话不可删除
    if (isAdmin && session?.is_main) return;
    setConfirmAction({ type: 'delete', sessionId: id });
  };

  const handleConfirmAction = async () => {
    if (!confirmAction) return;
    switch (confirmAction.type) {
      case 'delete':
        if (confirmAction.sessionId) {
          await deleteSession(confirmAction.sessionId);
        }
        break;
      case 'clearMain':
        await clearMainSession();
        break;
      case 'deleteAll':
        await deleteAllSessions();
        break;
    }
    setConfirmAction(null);
  };

  const cancelConfirm = () => setConfirmAction(null);

  /** 格式化时间戳为可读字符串 */
  const formatTime = (ts: string | number): string => {
    if (!ts) return '';
    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');
  };

  return (
    <aside className="h-full bg-white/70 dark:bg-gray-900/70 backdrop-blur-md border-r border-pink-100 dark:border-pink-900 flex flex-col">
      {/* 主对话按钮 (仅管理员可见) */}
      {isAdmin && (
        <div className="p-3 border-b border-pink-100 dark:border-pink-900 flex gap-2">
          <button
            onClick={handleMainSession}
            className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 bg-amber-50 hover:bg-amber-100 dark:bg-amber-900/20 dark:hover:bg-amber-900/30 text-amber-600 dark:text-amber-400 rounded-xl text-sm font-medium transition-colors border border-amber-200 dark:border-amber-800"
            title="回到主对话"
          >
            <span>🏠</span>
            <span>主对话</span>
          </button>
          <button
            onClick={() => setConfirmAction({ type: 'clearMain' })}
            className="flex items-center justify-center px-2 py-2 bg-red-50 hover:bg-red-100 dark:bg-red-900/20 dark:hover:bg-red-900/30 text-red-400 hover:text-red-500 rounded-xl text-sm transition-colors border border-red-200 dark:border-red-800"
            title="清空主对话消息"
          >
            <span>🗑️</span>
          </button>
        </div>
      )}

      {/* 新对话按钮 */}
      <div className="p-4 border-b border-pink-100 dark:border-pink-900">
        <button
          onClick={handleNewChat}
          className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-pink-400 hover:bg-pink-500 text-white rounded-xl text-sm font-medium transition-colors"
        >
          <span>+</span>
          <span>新对话</span>
        </button>
      </div>

      {/* 会话列表 */}
      <div className="flex-1 overflow-y-auto py-2">
        {displaySessions.length === 0 ? (
          <p className="text-xs text-gray-400 text-center py-8">
            还没有对话哦，开始和昔涟聊天吧 ♪
          </p>
        ) : (
          displaySessions.map((session) => {
            const isMainSession = session.is_main;
            const isActive = currentSessionId === session.id;
            // 管理员主对话不可删除
            const canDelete = !(isAdmin && isMainSession);

            return (
              <div
                key={session.id}
                onClick={() => handleSelectSession(session.id)}
                className={`
                  group flex items-center justify-between px-4 py-2.5 mx-2 rounded-lg cursor-pointer transition-colors
                  ${
                    isActive
                      ? 'bg-pink-50 dark:bg-pink-900/30 text-pink-600'
                      : 'hover:bg-gray-50 dark:hover:bg-gray-800 text-gray-600 dark:text-gray-300'
                  }
                `}
              >
                <div className="flex items-center gap-2 min-w-0 flex-1">
                  <CyreneAvatar size="sm" />
                  <div className="min-w-0">
                    <p className="text-sm font-medium truncate">
                      {isMainSession ? '🏠 ' : ''}
                      {session.title || '新的对话'}
                    </p>
                    <p className="text-xs text-gray-400 truncate">
                      {session.message_count != null
                        ? `${session.message_count} 条消息`
                        : ''}
                      {session.updated_at
                        ? `${session.message_count != null ? ' · ' : ''}${formatTime(session.updated_at)}`
                        : ''}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-0.5 relative">
                  {/* 导出按钮 */}
                  <div className="relative">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setExportMenuId(exportMenuId === session.id ? null : session.id);
                      }}
                      className="opacity-0 group-hover:opacity-100 p-1 text-gray-400 hover:text-blue-400 transition-all"
                      title="导出会话"
                      disabled={exportingId === session.id}
                    >
                      {exportingId === session.id ? (
                        <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                        </svg>
                      ) : (
                        <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="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                          />
                        </svg>
                      )}
                    </button>
                    {/* 格式选择下拉菜单 */}
                    {exportMenuId === session.id && (
                      <div className="absolute right-0 top-full mt-1 z-40 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-1 min-w-[120px]">
                        {(['json', 'markdown', 'txt'] as ExportFormat[]).map((fmt) => (
                          <button
                            key={fmt}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleExport(session.id, fmt);
                            }}
                            className="w-full text-left px-3 py-1.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                          >
                            {fmt === 'json' && '📦 JSON'}
                            {fmt === 'markdown' && '📝 Markdown'}
                            {fmt === 'txt' && '📄 TXT'}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                  {/* 删除按钮 */}
                  {canDelete && (
                    <button
                      onClick={(e) => handleDeleteClick(e, session.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>

      {/* Admin 管理导航 */}
      {isAdmin && (
        <div className="px-3 pt-2 border-t border-pink-100 dark:border-pink-900 space-y-1">
          <p className="px-1 text-[10px] text-gray-400 uppercase tracking-wider">管理</p>
          <AdminNavButton page="admin-models" icon="🤖" label="模型配置" />
          <AdminNavButton page="admin-dashboard" icon="📊" label="仪表盘" />
        </div>
      )}

      {/* 底部：记忆管理 + 一键清空所有对话 */}
      <div className="p-3 border-t border-pink-100 dark:border-pink-900 space-y-2">
        {/* 个人资料 */}
        <button
          onClick={() => usePageStore.getState().setPage('profile')}
          className="w-full flex items-center justify-center gap-1.5 px-3 py-2 bg-blue-50 hover:bg-blue-100 dark:bg-blue-900/20 dark:hover:bg-blue-900/30 text-blue-500 hover:text-blue-600 rounded-xl text-xs font-medium transition-colors border border-blue-200 dark:border-blue-800"
        >
          <span>👤</span>
          <span>个人资料</span>
        </button>
        {onMemoryClick && (
          <button
            onClick={onMemoryClick}
            className="w-full flex items-center justify-center gap-1.5 px-3 py-2 bg-purple-50 hover:bg-purple-100 dark:bg-purple-900/20 dark:hover:bg-purple-900/30 text-purple-500 hover:text-purple-600 rounded-xl text-xs font-medium transition-colors border border-purple-200 dark:border-purple-800"
          >
            <span>🧠</span>
            <span>记忆管理</span>
          </button>
        )}
        <button
          onClick={() => setConfirmAction({ type: 'deleteAll' })}
          className="w-full flex items-center justify-center gap-1.5 px-3 py-2 bg-red-50 hover:bg-red-100 dark:bg-red-900/20 dark:hover:bg-red-900/30 text-red-400 hover:text-red-500 rounded-xl text-xs font-medium transition-colors border border-red-200 dark:border-red-800"
        >
          <span>🗑️</span>
          <span>清空所有对话</span>
        </button>
        <div className="flex items-center gap-2 mt-3 text-xs text-gray-400">
          <CyreneAvatar size="sm" />
          <div>
            <p className="font-medium text-pink-400">昔涟</p>
            <p>v0.1.0 MVP</p>
          </div>
        </div>
      </div>

      {/* 确认弹窗 */}
      {confirmAction && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 m-4 max-w-sm w-full border border-pink-100 dark:border-pink-700">
            <h3 className="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-2">
              {confirmAction.type === 'delete'
                ? '删除会话'
                : confirmAction.type === 'clearMain'
                  ? '清空主对话'
                  : '清空所有对话'}
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
              {confirmAction.type === 'delete'
                ? '确定要删除这个会话吗？此操作不会删除记忆。'
                : confirmAction.type === 'clearMain'
                  ? '确定要清空主对话的所有消息吗？此操作不会删除记忆。'
                  : '确定要删除所有对话吗？此操作不会删除记忆。管理员将回到主对话，普通用户进入新对话。'}
            </p>
            <div className="flex justify-end gap-3">
              <button
                onClick={cancelConfirm}
                className="px-4 py-2 rounded-lg text-sm text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleConfirmAction}
                className="px-4 py-2 rounded-lg text-sm bg-red-400 hover:bg-red-500 text-white font-medium transition-colors"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      )}
    </aside>
  );
}

/** Admin 导航按钮 */
function AdminNavButton({ page, icon, label }: { page: string; icon: string; label: string }) {
  const currentPage = usePageStore((s) => s.currentPage);
  const setPage = usePageStore((s) => s.setPage);
  const isActive = currentPage === page;

  return (
    <button
      onClick={() => setPage(page as 'admin-models' | 'admin-dashboard')}
      className={`w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${
        isActive
          ? 'bg-pink-50 dark:bg-pink-900/30 text-pink-600'
          : 'text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-800 hover:text-gray-700 dark:hover:text-gray-300'
      }`}
    >
      <span>{icon}</span>
      <span>{label}</span>
    </button>
  );
}
