import { useState, useEffect } from 'react';
import { Layout, Avatar, Button as AntButton, Typography, Tooltip, Breadcrumb } from 'antd';
import { UserOutlined, LogoutOutlined, HomeOutlined } from '@ant-design/icons'

import styled from 'styled-components';

import { useRecoilState } from 'recoil';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { AuthLogout, AuthInfo } from '../../../apis';
import { authList } from '../../../store/authList';
import { alertTypes } from '../../../assets/data/types';
import { useAlert } from '../../../context/AlertProvider';
import { menuConfig } from '../../../assets/data/menuConfig';

const { Header } = Layout;
const { Text } = Typography;

const Profile = () => {
	const location = useLocation();
	const { showModal } = useAlert();
	const [infoData, setInfoData] = useRecoilState(authList);

	const navigate = useNavigate();

	const handleLogout = () => {
		const token = sessionStorage.getItem('token');
		AuthLogout(token);

		sessionStorage.removeItem('token');

		navigate('/');
	};

	const fetchData = async () => {
		const token = sessionStorage.getItem('token');
		await AuthInfo(token).then(data => {
			setInfoData(data);
		});
	};

	useEffect(() => {
		fetchData();
	}, []);

	// 필수값 입력 모달창
	const handleErrorModal = () => {
		showModal('USER_LOGOUT_CONFIRM', {
			type: alertTypes.confirm,
			onConfirm: () => handleLogout()
		});
	};

	// 카테고리별 첫 번째 아이템 링크 찾기
	const getFirstItemLink = (categoryKey) => {
		const category = menuConfig[categoryKey];
		if (!category || !category.items) return `/${categoryKey}`;

		// 첫 번째 visible 아이템 찾기
		const firstVisibleItem = Object.entries(category.items)
			.find(([_, item]) => item.view !== false);

		if (!firstVisibleItem) return `/${categoryKey}`;
		return `/${categoryKey}/${firstVisibleItem[0]}`;
	};

	const pathSnippets = location.pathname.split('/').filter(i => i);

	const breadcrumbItems = [
		{
			title: <Link to="/"><HomeOutlined /></Link>,
		}
	];

	if (pathSnippets.length > 0) {
		// 첫 번째 경로 (메인 카테고리)
		const mainCategory = pathSnippets[0];
		if (menuConfig[mainCategory]) {
			const firstItemLink = getFirstItemLink(mainCategory);

			breadcrumbItems.push({
				title: <Link to={firstItemLink}>{menuConfig[mainCategory].title}</Link>
			});

			// 두 번째 경로 (서브 카테고리)
			if (pathSnippets.length > 1) {
				const subCategory = pathSnippets[1];
				if (menuConfig[mainCategory].items[subCategory]) {
					breadcrumbItems.push({
						title: menuConfig[mainCategory].items[subCategory].title
					});
				}
			}
		}
	}

	return (
		<>
			<StyledHeader>
				<StyledBreadcrumb items={breadcrumbItems} />
				<ProfileContainer>
					<StyledAvatar
						size={32}
						icon={<UserOutlined />}
					/>
					{infoData.name &&
						<StyledUsername>
							{infoData.name.length > 20 ? infoData.name.slice(0, 20) + '...' : infoData.name}님
						</StyledUsername>
					}
					<Tooltip title="로그아웃">
						<StyledLogoutButton
							type="text"
							icon={<LogoutOutlined />}
							onClick={handleErrorModal}
						/>
					</Tooltip>
				</ProfileContainer>

			</StyledHeader>

		</>
	);
};

export default Profile;

const StyledHeader = styled(Header)`
    background: #f6f6f6;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 64px;
`;

const StyledBreadcrumb = styled(Breadcrumb)`
	font-size: 15px;
    font-weight: 600;
`;

const ProfileContainer = styled.div`
	display: flex;
	align-items: center;
	gap: 12px;
`;

const StyledAvatar = styled(Avatar)`
`;

const StyledUsername = styled(Text)`
    font-weight: 600;
    font-size: 18px;
    color: rgba(0, 0, 0, 0.85);
`;

const StyledLogoutButton = styled(AntButton)`
    color: rgba(0, 0, 0, 0.45);
    transition: color 0.3s;
    font-size: 18px;

    &:hover {
        color: #1677ff;
        background: transparent;
    }

`;
