import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { Dropdown, Space } from 'antd';
import { UserOutlined, LogoutOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { logout } from '@/store/userSlice';
import type { RootState } from '@/store';
import { useToast } from '@/components/ui/use-toast';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { AlertCircle } from 'lucide-react';
import { shallowEqual } from 'react-redux';

/**
 * 用户面板组件
 * 
 * 功能：
 * 1. 显示用户信息
 * 2. 提供退出登录功能
 * 3. 使用 React.memo 和 shallowEqual 优化渲染
 */
const UserPanel: React.FC = React.memo(() => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { toast } = useToast();
  const [logoutDialogOpen, setLogoutDialogOpen] = useState(false);

  // 使用 shallowEqual 优化，只有 userInfo 变化时才重新渲染
  const userInfo = useSelector(
    (state: RootState) => state.user.userInfo,
    shallowEqual
  );

  const handleLogout = () => {
    setLogoutDialogOpen(true);
  };

  const confirmLogout = async () => {
    dispatch(logout());
    navigate('/login', { replace: true });
  };

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'userInfo',
      icon: <UserOutlined />,
      label: (
        <div style={{ padding: '4px 0' }}>
          <div>当前用户：{userInfo?.nickname || userInfo?.username}</div>
          {userInfo?.email && (
            <div style={{ fontSize: '12px', color: '#999' }}>
              {userInfo.email}
            </div>
          )}
        </div>
      ),
      disabled: true,
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
    },
  ];

  return (
    <>
      <Dropdown menu={{ items: userMenuItems }} trigger={['hover']}>
        <Space className="cursor-pointer">
          <UserOutlined className="text-sm" />
          <span className="text-sm">
            {userInfo?.nickname || userInfo?.username}
          </span>
        </Space>
      </Dropdown>

      {/* 退出登录确认对话框 */}
      <ConfirmDialog
        open={logoutDialogOpen}
        onOpenChange={setLogoutDialogOpen}
        title={
          <div className="flex items-center gap-2">
            <AlertCircle className="h-5 w-5 text-amber-500" />
            确认退出
          </div>
        }
        description="确定要退出系统吗？"
        onConfirm={confirmLogout}
        onSuccess={() => {
          toast({
            title: '退出成功',
            description: '已成功退出系统',
          });
        }}
        confirmText="确定"
      />
    </>
  );
});

UserPanel.displayName = 'UserPanel';

export default UserPanel;

