import MenuIcon from '@mui/icons-material/Menu'
import HomeIcon from '@mui/icons-material/Home'
import PeopleAltIcon from '@mui/icons-material/PeopleAlt'
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'
import RefreshIcon from '@mui/icons-material/Refresh'
import TranslateIcon from '@mui/icons-material/Translate'
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'
import ChevronRightIcon from '@mui/icons-material/ChevronRight'
import MuiDrawer from '@mui/material/Drawer'
import {
    AppBar,
    Avatar,
    Box,
    Button,
    Container,
    Divider,
    IconButton,
    Stack,
    Toolbar,
    Typography,
    useMediaQuery,
} from '@mui/material'
import {styled, useTheme} from '@mui/material/styles'
import type {CSSObject, Theme} from '@mui/material/styles'
import {Link, Outlet, useRouterState} from '@tanstack/react-router'
import {TanStackRouterDevtools} from '@tanstack/react-router-devtools'
import {useState} from 'react'

const menuItems = [
    {label: '首页', to: '/', icon: <HomeIcon fontSize="small"/>},
    {label: '角色', to: '/characters', icon: <PeopleAltIcon fontSize="small"/>},
    {label: '神器', to: '/artifacts', icon: <AutoAwesomeIcon fontSize="small"/>},
]

const drawerWidth = 260
const collapsedWidth = 76

const openedMixin = (theme: Theme): CSSObject => ({
    width: drawerWidth,
    transition: theme.transitions.create('width', {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.enteringScreen,
    }),
    overflowX: 'hidden',
})

const closedMixin = (theme: Theme): CSSObject => ({
    width: collapsedWidth,
    transition: theme.transitions.create('width', {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
    }),
    overflowX: 'hidden',
})

const StyledDrawer = styled(MuiDrawer, {
    shouldForwardProp: (prop) => prop !== 'open',
})(({theme, open}) => ({
    width: drawerWidth,
    flexShrink: 0,
    whiteSpace: 'nowrap',
    boxSizing: 'border-box',
    ...(open && {
        ...openedMixin(theme),
        '& .MuiDrawer-paper': {
            ...openedMixin(theme),
        },
    }),
    ...(!open && {
        ...closedMixin(theme),
        '& .MuiDrawer-paper': {
            ...closedMixin(theme),
        },
    }),
    '& .MuiDrawer-paper': {
        height: '100vh',
        background:
            'linear-gradient(180deg, rgba(31,26,38,0.46) 0%, rgba(25,21,34,0.52) 100%)',
        borderRight: 'none',
        boxShadow: 'none',
    },
}))

export function RootLayout() {
    const pathname = useRouterState({select: (state) => state.location.pathname})
    const theme = useTheme()
    const isMobile = useMediaQuery(theme.breakpoints.down('md'))
    const [drawerOpen, setDrawerOpen] = useState(false)
    const [collapsed, setCollapsed] = useState(false)

    const sidebarContent = (
        <Box
            sx={{
                height: '100%',
                color: '#f3ede6',
                display: 'flex',
                flexDirection: 'column',
            }}
        >
            <Stack spacing={2} sx={{p: 2.5}}>
                <Stack
                    direction="row"
                    spacing={1.5}
                    alignItems="center"
                    justifyContent={collapsed ? 'center' : 'flex-start'}
                >
                    <Avatar
                        src="/hero-avatar.png"
                        sx={{
                            width: 36,
                            height: 36,
                            border: '1px solid rgba(255,255,255,0.2)',
                            background: 'rgba(255,255,255,0.08)',
                        }}
                    />
                    {collapsed ? null : (
                        <Stack spacing={0.2}>
                            <Typography sx={{fontWeight: 700, letterSpacing: 1}}>第七史诗资料馆</Typography>
                            <Typography variant="body2" sx={{color: 'rgba(243,237,230,0.72)'}}>
                                Epic Seven Archives
                            </Typography>
                        </Stack>
                    )}
                </Stack>
            </Stack>

            <Divider sx={{borderColor: 'rgba(255,255,255,0.12)'}}/>

            <Stack spacing={1} sx={{px: 1.5, py: 2, flex: 1}}>
                {menuItems.map((item) => {
                    const active = pathname === item.to
                    return (
                        <Button
                            key={item.to}
                            component={Link}
                            to={item.to}
                            startIcon={item.icon}
                            onClick={() => setDrawerOpen(false)}
                            sx={{
                                justifyContent: collapsed ? 'center' : 'flex-start',
                                color: active ? '#1f1a26' : '#f3ede6',
                                background: active ? '#f7d9b4' : 'rgba(255,255,255,0.06)',
                                borderRadius: 2,
                                textTransform: 'none',
                                fontWeight: 600,
                                minHeight: 44,
                                position: 'relative',
                                overflow: 'hidden',
                                transition: 'transform 160ms ease, background 160ms ease, box-shadow 160ms ease',
                                '& .MuiButton-startIcon': {
                                    margin: 0,
                                },
                                '&::after': {
                                    content: '""',
                                    position: 'absolute',
                                    inset: 0,
                                    background:
                                        active
                                            ? 'radial-gradient(circle at 18% 50%, rgba(255,229,196,0.6), transparent 60%)'
                                            : 'none',
                                    opacity: 0.9,
                                },
                                '&:hover': {
                                    transform: collapsed ? 'none' : 'translateX(2px)',
                                    background: active ? '#f4cfa2' : 'rgba(255,255,255,0.12)',
                                    boxShadow: '0 6px 18px rgba(0,0,0,0.2)',
                                },
                            }}
                        >
                            {collapsed ? null : item.label}
                        </Button>
                    )
                })}
            </Stack>

            <Divider sx={{borderColor: 'rgba(255,255,255,0.12)'}}/>

            <Stack spacing={1} sx={{px: 1.5, py: 2}}>
                <Button
                    startIcon={<TranslateIcon fontSize="small"/>}
                    sx={{
                        justifyContent: collapsed ? 'center' : 'flex-start',
                        color: '#f3ede6',
                        background: 'rgba(255,255,255,0.06)',
                        borderRadius: 2,
                        textTransform: 'none',
                        minHeight: 40,
                        '& .MuiButton-startIcon': {margin: 0},
                    }}
                >
                    {collapsed ? null : '中文'}
                </Button>
                <Button
                    startIcon={<RefreshIcon fontSize="small"/>}
                    sx={{
                        justifyContent: collapsed ? 'center' : 'flex-start',
                        color: '#f3ede6',
                        background: 'rgba(255,255,255,0.06)',
                        borderRadius: 2,
                        textTransform: 'none',
                        minHeight: 40,
                        '& .MuiButton-startIcon': {margin: 0},
                    }}
                >
                    {collapsed ? null : '刷新数据'}
                </Button>
            </Stack>

            <Divider sx={{borderColor: 'rgba(255,255,255,0.12)'}}/>

            <Box sx={{p: 1.5}}>
                <Button
                    fullWidth
                    onClick={() => setCollapsed((prev) => !prev)}
                    startIcon={collapsed ? <ChevronRightIcon fontSize="small"/> : <ChevronLeftIcon fontSize="small"/>}
                    sx={{
                        justifyContent: collapsed ? 'center' : 'flex-start',
                        color: '#f3ede6',
                        background: 'rgba(255,255,255,0.06)',
                        borderRadius: 2,
                        textTransform: 'none',
                        minHeight: 40,
                        '& .MuiButton-startIcon': {margin: 0},
                    }}
                >
                    {collapsed ? null : '收起菜单'}
                </Button>
            </Box>
        </Box>
    )

    return (
        <Box
            sx={{
                minHeight: '100vh',
            }}
        >
            {isMobile ? (
                <AppBar position="sticky" elevation={0} sx={{background: 'rgba(31,26,38,0.75)'}}>
                    <Toolbar sx={{gap: 1.5}}>
                        <IconButton color="inherit" onClick={() => setDrawerOpen(true)}>
                            <MenuIcon/>
                        </IconButton>
                        <Typography sx={{fontWeight: 700, letterSpacing: 1}}>第七史诗资料馆</Typography>
                    </Toolbar>
                </AppBar>
            ) : null}

            <Box sx={{display: 'flex', minHeight: '100vh'}}>
                {isMobile ? null : (
                    <StyledDrawer variant="permanent" open={!collapsed}>
                        {sidebarContent}
                    </StyledDrawer>
                )}

                <Box sx={{flex: 1, minWidth: 0}}>
                    <Container sx={{py: {xs: 3, md: 4}}}>
                        <Outlet/>
                    </Container>
                </Box>
            </Box>

            <MuiDrawer
                anchor="left"
                open={drawerOpen}
                onClose={() => setDrawerOpen(false)}
                PaperProps={{
                    sx: {
                        background:
                            'linear-gradient(180deg, rgba(31,26,38,0.46) 0%, rgba(25,21,34,0.52) 100%)',
                        borderRight: 'none',
                        boxShadow: 'none',
                    },
                }}
            >
                <Box sx={{width: 260}}>{sidebarContent}</Box>
            </MuiDrawer>

            {import.meta.env.DEV ? <TanStackRouterDevtools position="bottom-right"/> : null}
        </Box>
    )
}
