import { business } from '@/services';
import { BellOutlined, LoadingOutlined, MoreOutlined } from '@ant-design/icons';
import { history, useIntl } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Badge, Dropdown, Empty, List, message, Spin } from 'antd';
import React, { useMemo, useState } from 'react';
import styles from './NotificationMessage.module.less';

interface NotificationMessageProps {
	adminId?: string;
}

const NotificationMessage: React.FC<NotificationMessageProps> = ({
	adminId,
}) => {
	const intl = useIntl();
	const [dropdownOpen, setDropdownOpen] = useState(false);

	// 获取未读消息数量
	const { data: unreadCountData, refresh: refreshUnreadCount } = useRequest(
		() =>
			business.messageReceiver.getUnreadCount({
				messageReceiverUnreadCountQry: {
					adminId: adminId || '',
				},
			}),
		{
			ready: !!adminId,
			refreshDeps: [adminId],
		},
	);

	const unreadCount = unreadCountData?.data || 0;

	// 获取消息列表（只获取前5条未读消息）
	const {
		data: messageListData,
		loading: messageListLoading,
		refresh: refreshMessageList,
	} = useRequest(
		() =>
			business.messageReceiver.pageMessageReceiver({
				messageReceiverPageQry: {
					pageIndex: 1,
					pageSize: 5,
				},
			}),
		{
			ready: dropdownOpen && !!adminId,
			refreshDeps: [dropdownOpen, adminId],
		},
	);

	const messageList = messageListData?.data || [];

	// 标记已读
	const { run: markAsRead } = useRequest(
		(messageReceiverId: string) =>
			business.messageReceiver.markReadMessageReceiver({
				messageReceiverId: messageReceiverId,
			}),
		{
			manual: true,
			onSuccess: () => {
				refreshUnreadCount();
				refreshMessageList();
			},
			onError: (error) => {
				message.error(
					intl.formatMessage({ id: 'notification.markReadFailed' }),
				);
				console.error('标记已读失败:', error);
			},
		},
	);

	// 点击消息项
	const handleMessageClick = (item: BusinessAPI.MessageReceiverVO) => {
		if (!item.isRead) {
			markAsRead(item.messageReceiverId);
		}
		// 可以跳转到消息详情页面
		// history.push(`/operation/settings/notify/message-record`);
	};

	// 查看更多消息
	const handleViewMore = () => {
		setDropdownOpen(false);
		history.push('/operation/settings/notify/message-record');
	};

	// 下拉菜单内容
	const dropdownContent = useMemo(() => {
		return (
			<div className={styles.dropdownContent}>
				<div className={styles.header}>
					<span className={styles.title}>
						{intl.formatMessage({ id: 'notification.title' })}
					</span>
					{unreadCount > 0 && (
						<span className={styles.count}>
							{intl.formatMessage(
								{ id: 'notification.unreadCount' },
								{ count: unreadCount },
							)}
						</span>
					)}
				</div>

				<div className={styles.messageList}>
					{messageListLoading ? (
						<div className={styles.loadingWrapper}>
							<Spin indicator={<LoadingOutlined spin />} />
						</div>
					) : messageList.length > 0 ? (
						<List
							dataSource={messageList}
							renderItem={(item: BusinessAPI.MessageReceiverVO) => (
								<List.Item
									key={item.messageReceiverId}
									className={`${styles.messageItem} ${
										!item.isRead ? styles.unread : ''
									}`}
									onClick={() => handleMessageClick(item)}
								>
									<div className={styles.messageContent}>
										<div className={styles.messageTitle}>
											{item.messageVO?.title || '消息通知'}
											{!item.isRead && <span className={styles.unreadDot} />}
										</div>
										<div className={styles.messageDesc}>
											{item.messageVO?.content || ''}
										</div>
										<div className={styles.messageTime}>{item.createdAt}</div>
									</div>
								</List.Item>
							)}
						/>
					) : (
						<div className={styles.emptyWrapper}>
							<Empty
								image={Empty.PRESENTED_IMAGE_SIMPLE}
								description={intl.formatMessage({
									id: 'notification.noMessages',
								})}
							/>
						</div>
					)}
				</div>

				{messageList.length > 0 && (
					<div className={styles.footer} onClick={handleViewMore}>
						<span>{intl.formatMessage({ id: 'notification.viewMore' })}</span>
						<MoreOutlined />
					</div>
				)}
			</div>
		);
	}, [
		messageList,
		messageListLoading,
		unreadCount,
		intl,
		markAsRead,
		handleMessageClick,
		handleViewMore,
	]);

	return (
		<Dropdown
			open={dropdownOpen}
			onOpenChange={setDropdownOpen}
			trigger={['click']}
			placement="bottomRight"
			dropdownRender={() => dropdownContent}
		>
			<Badge
				count={unreadCount}
				overflowCount={99}
				size="small"
				offset={[-5, 5]}
			>
				<BellOutlined className={styles.bellIcon} />
			</Badge>
		</Dropdown>
	);
};

export default NotificationMessage;
