import {
	LogoutOutlined,
	SettingOutlined,
	UserSwitchOutlined,
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Dropdown, message, Modal, Radio } from 'antd';
import React, { ReactNode, useEffect, useState } from 'react';

const Avatar: React.FC<{ children: ReactNode }> = ({ children }) => {
	const { logout } = useModel('useUser', (model) => ({
		logout: model.logout,
	}));

	const [userRoleVOList, setUserRoleVOList] = useState<
		BusinessAPI.UserRoleVO[]
	>([]);
	const [isModalVisible, setIsModalVisible] = useState(false);
	const [selectedRoleId, setSelectedRoleId] = useState<string>('');

	useEffect(() => {
		const roles = JSON.parse(
			localStorage.getItem('userRoleVOList') || '[]',
		) as BusinessAPI.UserRoleVO[];
		setUserRoleVOList(roles);

		// 获取当前选中的角色
		const currentRoleSlug = localStorage.getItem('roleSlug') || '';
		const currentRole = roles.find((role) => role.slug === currentRoleSlug);
		if (currentRole) {
			setSelectedRoleId(currentRole.roleId);
		}
	}, []);

	const handleSwitchRole = () => {
		setIsModalVisible(true);
	};

	const handleModalOk = () => {
		// 保存选中的角色到localStorage
		const selectedRole = userRoleVOList.find(
			(role) => role.roleId === selectedRoleId,
		);
		if (selectedRole) {
			localStorage.setItem('roleSlug', selectedRole.slug);
			message.success('角色切换成功，请重新加载页面');
			setIsModalVisible(false);
			// 重新加载页面以应用新的角色权限
			window.location.reload();
		}
	};

	const handleModalCancel = () => {
		setIsModalVisible(false);
	};

	return (
		<>
			<Dropdown
				menu={{
					items: [
						...(userRoleVOList.length > 1
							? [
									{
										key: 'switch',
										icon: <UserSwitchOutlined />,
										label: '切换角色',
										onClick: handleSwitchRole,
									},
								]
							: []),
						{
							key: 'setting',
							icon: <SettingOutlined />,
							label: '账号设置',
							onClick: async () => {
								history.push('/operation/settings/account');
							},
						},
						{
							key: 'logout',
							icon: <LogoutOutlined />,
							label: '退出登录',
							onClick: async () => logout(),
						},
					],
				}}
			>
				{children}
			</Dropdown>

			<Modal
				title="切换角色"
				open={isModalVisible}
				onOk={handleModalOk}
				onCancel={handleModalCancel}
				okText="确认"
				cancelText="取消"
			>
				<Radio.Group
					onChange={(e) => setSelectedRoleId(e.target.value)}
					value={selectedRoleId}
					style={{ width: '100%' }}
				>
					<div className="space-y-2">
						{userRoleVOList.map((role) => (
							<div
								key={role.roleId}
								className="flex items-center p-2 hover:bg-gray-50 rounded"
							>
								<Radio value={role.roleId}>{role.name}</Radio>
							</div>
						))}
					</div>
				</Radio.Group>
			</Modal>
		</>
	);
};

export default Avatar;
