import { useRef, useEffect, useState, useCallback } from 'react';
import { CyreneAvatar } from '@/components/persona/CyreneAvatar';
import { MoodIndicator } from '@/components/persona/MoodIndicator';
import { useAuth } from '@/hooks/useAuth';
import { usePWA } from '@/hooks/usePWA';
import { useNotificationStore } from '@/store/notificationStore';
import { useSessionStore } from '@/store/sessionStore';
import { getToken } from '@/api/client';
import { ReminderPanel } from '@/components/layout/ReminderPanel';
import { BriefingPanel } from '@/components/layout/BriefingPanel';
import { AutomationPanel } from '@/components/layout/AutomationPanel';
import { FilePanel } from '@/components/layout/FilePanel';
import { KnowledgePanel } from '@/components/layout/KnowledgePanel';
import type { AppNotification } from '@/types/chat';

interface HeaderProps {
  onMenuClick: () => void;
  onSearchClick: () => void;
}

/** 通知类型对应的图标和颜色 */
const NOTIF_STYLES: Record<string, { icon: string; bg: string; text: string }> = {
  info: { icon: 'ℹ️', bg: 'bg-blue-50 dark:bg-blue-900/30', text: 'text-blue-600 dark:text-blue-400' },
  warning: { icon: '⚠️', bg: 'bg-yellow-50 dark:bg-yellow-900/30', text: 'text-yellow-600 dark:text-yellow-400' },
  success: { icon: '✅', bg: 'bg-green-50 dark:bg-green-900/30', text: 'text-green-600 dark:text-green-400' },
  thinking: { icon: '💭', bg: 'bg-purple-50 dark:bg-purple-900/30', text: 'text-purple-600 dark:text-purple-400' },
  reminder: { icon: '🔔', bg: 'bg-pink-50 dark:bg-pink-900/30', text: 'text-pink-600 dark:text-pink-400' },
};

/** 格式化时间 */
function formatTime(ts: string): string {
  try {
    const d = new Date(ts);
    const now = new Date();
    const diffMs = now.getTime() - d.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}小时前`;
    return d.toLocaleDateString('zh-CN');
  } catch {
    return ts;
  }
}

export function Header({ onMenuClick, onSearchClick }: HeaderProps) {
  const { logout } = useAuth();
  const {
    notifications,
    unreadCount,
    isOpen,
    toggleOpen,
    setOpen,
    markAsRead,
    markAllAsRead,
  } = useNotificationStore();
  const setCurrentSessionId = useSessionStore((s) => s.setCurrentSessionId);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // PWA Hook
  const { isInstallable, isInstalled, hasUpdate, install, update } = usePWA();

  // 下拉面板标签页切换
  const [dropdownTab, setDropdownTab] = useState<'notifications' | 'reminders' | 'briefing' | 'automation' | 'files' | 'knowledge'>('notifications');

  // 获取当前用户 ID
  const userId = localStorage.getItem('user_id') || '';

  // 健康检查指示器
  const [apiOnline, setApiOnline] = useState<boolean | null>(null);
  const checkHealth = useCallback(async () => {
    try {
      const API_BASE = import.meta.env.VITE_API_URL || '/api/v1';
      const resp = await fetch(`${API_BASE}/health`);
      const data = await resp.json();
      setApiOnline(data?.status === 'ok');
    } catch {
      setApiOnline(false);
    }
  }, []);

  useEffect(() => {
    checkHealth();
    const interval = setInterval(checkHealth, 30000);
    return () => clearInterval(interval);
  }, [checkHealth]);

  // 点击外部关闭下拉
  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isOpen, setOpen]);

  const handleNotifClick = (n: AppNotification) => {
    markAsRead(n.id);
    if (n.data?.session_id) {
      setCurrentSessionId(n.data.session_id as string);
    }
    setOpen(false);
  };

  return (
    <header className="flex items-center justify-between px-4 py-2 border-b border-pink-100 dark:border-pink-900 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm">
      <div className="flex items-center gap-3">
        {/* 移动端菜单按钮 */}
        <button
          onClick={onMenuClick}
          className="lg:hidden p-1 text-gray-400 hover:text-pink-500 transition-colors"
        >
          <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
          </svg>
        </button>

        <CyreneAvatar size="sm" />
        <div>
          <div className="flex items-center gap-1.5">
            <h1 className="text-base font-semibold text-pink-600 dark:text-pink-400">
              昔涟
            </h1>
            {apiOnline !== null && (
              <span
                className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${
                  apiOnline ? 'bg-green-400' : 'bg-red-400 animate-pulse'
                }`}
                title={apiOnline ? 'API 在线' : 'API 离线'}
              />
            )}
          </div>
          <MoodIndicator />
        </div>
      </div>

      <div className="flex items-center gap-1">
        {/* PWA 安装按钮 */}
        {isInstallable && !isInstalled && (
          <button
            onClick={install}
            className="p-1.5 text-gray-400 hover:text-pink-500 transition-colors rounded-lg"
            title="安装应用到桌面"
          >
            <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="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>
        )}

        {/* PWA 更新按钮 */}
        {hasUpdate && (
          <button
            onClick={update}
            className="px-2 py-1 text-xs font-medium text-white bg-pink-500 hover:bg-pink-600 rounded-full transition-colors"
            title="有新版本可用，点击更新"
          >
            更新
          </button>
        )}

        {/* 通知铃铛 */}
        <div className="relative" ref={dropdownRef}>
          <button
            onClick={toggleOpen}
            className="relative p-1.5 text-gray-400 hover:text-pink-500 transition-colors rounded-lg"
            title="通知"
          >
            <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="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
            </svg>
            {unreadCount > 0 && (
              <span className="absolute -top-0.5 -right-0.5 flex items-center justify-center w-4 h-4 text-[10px] font-bold text-white bg-red-500 rounded-full">
                {unreadCount > 99 ? '99+' : unreadCount}
              </span>
            )}
          </button>

          {/* 通知下拉列表 */}
          {isOpen && (
            <div className="absolute right-0 mt-2 w-80 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-xl z-50 overflow-hidden">
              {/* 标签页切换：通知 / 提醒 */}
              <div className="flex border-b border-gray-100 dark:border-gray-700">
                <button
                  onClick={() => setDropdownTab('notifications')}
                  className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
                    dropdownTab === 'notifications'
                      ? 'text-pink-500 border-b-2 border-pink-500'
                      : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
                  }`}
                >
                  通知
                  {unreadCount > 0 && (
                    <span className="ml-1 text-[10px] bg-red-500 text-white px-1 rounded-full">
                      {unreadCount > 99 ? '99+' : unreadCount}
                    </span>
                  )}
                </button>
                <button
                  onClick={() => setDropdownTab('reminders')}
                  className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
                    dropdownTab === 'reminders'
                      ? 'text-pink-500 border-b-2 border-pink-500'
                      : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
                  }`}
                >
                  提醒 ⏰
                </button>
                <button
                  onClick={() => setDropdownTab('briefing')}
                  className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
                    dropdownTab === 'briefing'
                      ? 'text-pink-500 border-b-2 border-pink-500'
                      : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
                  }`}
                >
                  简报 📋
                </button>
                <button
                	onClick={() => setDropdownTab('automation')}
                	className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
                		dropdownTab === 'automation'
                			? 'text-pink-500 border-b-2 border-pink-500'
                			: 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
                	}`}
                >
                	⚡ 自动化
                </button>
                <button
                	onClick={() => setDropdownTab('files')}
                	className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
                		dropdownTab === 'files'
                			? 'text-pink-500 border-b-2 border-pink-500'
                			: 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
                	}`}
                >
                	📁 文件
                </button>
                <button
                	onClick={() => setDropdownTab('knowledge')}
                	className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
                		dropdownTab === 'knowledge'
                			? 'text-pink-500 border-b-2 border-pink-500'
                			: 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
                	}`}
                >
                	📚 知识库
                </button>
              </div>

              {/* 通知面板 */}
              {dropdownTab === 'notifications' && (
                <div className="max-h-80 overflow-y-auto">
                  <div className="flex items-center justify-between px-4 py-2 border-b border-gray-50 dark:border-gray-700">
                    <h3 className="text-xs font-semibold text-gray-500 dark:text-gray-400">
                      最近通知
                    </h3>
                    {unreadCount > 0 && (
                      <button
                        onClick={() => markAllAsRead()}
                        className="text-[10px] text-pink-500 hover:text-pink-600 transition-colors"
                      >
                        全部已读
                      </button>
                    )}
                  </div>

                  {notifications.length === 0 ? (
                    <div className="px-4 py-8 text-center text-sm text-gray-400">
                      🔔 暂无通知
                    </div>
                  ) : (
                    <div className="divide-y divide-gray-100 dark:divide-gray-700">
                      {notifications.slice(0, 10).map((n) => {
                        const style = NOTIF_STYLES[n.type] || NOTIF_STYLES.info;
                        return (
                          <button
                            key={n.id}
                            onClick={() => handleNotifClick(n)}
                            className={`w-full text-left px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors flex items-start gap-3 ${
                              !n.read ? 'bg-pink-50/50 dark:bg-pink-900/10' : ''
                            }`}
                          >
                            <span className="text-lg mt-0.5 flex-shrink-0">{style.icon}</span>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2">
                                <span className={`text-xs font-medium ${style.text}`}>
                                  {n.title}
                                </span>
                                {!n.read && (
                                  <span className="w-2 h-2 bg-pink-500 rounded-full flex-shrink-0" />
                                )}
                              </div>
                              <p className="text-xs text-gray-500 dark:text-gray-400 truncate mt-0.5">
                                {n.body}
                              </p>
                              <span className="text-[10px] text-gray-400 mt-1 block">
                                {formatTime(n.timestamp)}
                              </span>
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
              )}

              {/* 提醒面板 */}
              {dropdownTab === 'reminders' && (
                <div className="max-h-80 overflow-y-auto">
                  <ReminderPanel userId={userId} onClose={() => setOpen(false)} />
                </div>
              )}

              {/* 简报面板 */}
              {dropdownTab === 'briefing' && (
                <div className="max-h-80 overflow-y-auto">
                  <BriefingPanel userId={userId} onClose={() => setOpen(false)} />
                </div>
              )}

              	{/* 自动化面板 */}
              	{dropdownTab === 'automation' && (
              		<div className="max-h-80 overflow-y-auto">
              			<AutomationPanel onClose={() => setOpen(false)} />
              		</div>
              	)}

              	{/* 文件面板 */}
              	{dropdownTab === 'files' && (
              		<div className="max-h-96 overflow-y-auto">
              			<FilePanel onClose={() => setOpen(false)} />
              		</div>
              	)}

              	{/* 知识库面板 */}
              	{dropdownTab === 'knowledge' && (
              		<div className="max-h-96 overflow-y-auto">
              			<KnowledgePanel onClose={() => setOpen(false)} />
              		</div>
              	)}
            </div>
          )}
        </div>

        {/* 搜索按钮 */}
        <button
          onClick={onSearchClick}
          className="p-1.5 text-gray-400 hover:text-pink-500 transition-colors rounded-lg"
          title="搜索消息 (Ctrl+K)"
        >
          <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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </button>

        <span className="text-xs text-gray-400 hidden sm:block">🌸 永远在你身边</span>
        <button
          onClick={logout}
          className="text-xs text-gray-400 hover:text-pink-500 transition-colors px-2 py-1"
        >
          退出
        </button>
      </div>
    </header>
  );
}
