import { Box, List, ListItemButton, ListItemText, Typography, Collapse, ListItemIcon } from '@mui/material';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import {
  LibraryBooksOutlined as KnowledgeBasesIcon,
  AccountTreeOutlined as AgentIcon,
  SettingsOutlined as SettingIcon,
  Person as PersonIcon,
  Group as GroupIcon,
  ExpandMore as ExpandMoreIcon,
  ExpandLess as ExpandLessIcon,

} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useMemo, useState } from 'react';

type MenuChild = {
  text: string;
  path: string;
  icon?: React.ComponentType<any>;
};

type MenuItem = {
  text: string;
  path: string;
  icon: React.ComponentType<any>;
  children?: MenuChild[];
};

const Sidebar = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { t } = useTranslation();

  const navItems: MenuItem[] = useMemo(() => ([
    { text: t('header.knowledgeBase'), path: '/knowledge', icon: KnowledgeBasesIcon },
    { text: t('header.agents'), path: '/agents', icon: AgentIcon },
    { text: t('header.models'), path: '/models', icon: AgentIcon },
    { text: t('header.mcp'), path: '/mcp', icon: AgentIcon },
    {
      text: t('header.setting'),
      path: '/setting',
      icon: SettingIcon,
      children: [
        { text: t('setting.profile'), path: '/setting/profile', icon: PersonIcon },
        { text: t('setting.team'), path: '/setting/teams', icon: GroupIcon },
      ],
    },
  ]), [t]);

  const [openGroup, setOpenGroup] = useState<Record<string, boolean>>({
    '/setting': location.pathname.startsWith('/setting'),
  });

  const toggleGroup = (path: string) => {
    setOpenGroup((prev) => ({ ...prev, [path]: !prev[path] }));
  };

  const isActivePath = (itemPath: string) => {
    if (itemPath === '/knowledge' && (location.pathname === '/' || location.pathname.startsWith('/knowledge'))) {
      return true;
    }
    return location.pathname === itemPath || location.pathname.startsWith(itemPath + '/');
  };

  return (
    <Box
      sx={{
        width: '240px',
        backgroundColor: '#1E1E24',
        color: '#DDD',
        height: '100vh',
        padding: '1rem 0',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <Typography
        sx={{
          fontSize: '1.05rem',
          fontWeight: 600,
          padding: '0 1.25rem 1rem',
          margin: '0 0 0.5rem',
          color: '#FFF',
          letterSpacing: '0.5px',
        }}
      >
        TERES AI
      </Typography>

      <List>
        {navItems.map((item) => {
          const IconComponent = item.icon;
          const hasChildren = Array.isArray(item.children) && item.children.length > 0;
          const isActive = isActivePath(item.path);

          return (
            <Box key={item.path}>
              {hasChildren ? (
                <ListItemButton
                  onClick={() => toggleGroup(item.path)}
                  sx={{
                    color: isActive ? '#FFF' : '#B9B9C2',
                    backgroundColor: isActive ? 'rgba(226,0,116,0.12)' : 'transparent',
                    borderLeft: isActive ? '4px solid' : '4px solid transparent',
                    borderLeftColor: isActive ? 'primary.main' : 'transparent',
                    fontWeight: isActive ? 600 : 'normal',
                    '&:hover': {
                      backgroundColor: 'rgba(255,255,255,0.05)',
                      color: '#FFF',
                    },
                    '& .MuiListItemText-primary': {
                      fontSize: '0.9rem',
                    },
                  }}
                >
                  <IconComponent sx={{ color: 'primary.main', marginRight: '12px', fontSize: '1.2rem' }} />
                  <ListItemText primary={item.text} />
                  {openGroup[item.path] ? (
                    <ExpandLessIcon sx={{ marginLeft: 'auto', color: '#B9B9C2' }} />
                  ) : (
                    <ExpandMoreIcon sx={{ marginLeft: 'auto', color: '#B9B9C2' }} />
                  )}
                </ListItemButton>
              ) : (
                <Link to={item.path} style={{ textDecoration: 'none', color: 'inherit' }}>
                  <ListItemButton
                    sx={{
                      color: isActive ? '#FFF' : '#B9B9C2',
                      backgroundColor: isActive ? 'rgba(226,0,116,0.12)' : 'transparent',
                      borderLeft: isActive ? '4px solid' : '4px solid transparent',
                      borderLeftColor: isActive ? 'primary.main' : 'transparent',
                      fontWeight: isActive ? 600 : 'normal',
                      '&:hover': {
                        backgroundColor: 'rgba(255,255,255,0.05)',
                        color: '#FFF',
                      },
                      '& .MuiListItemText-primary': {
                        fontSize: '0.9rem',
                      },
                    }}
                  >
                    <IconComponent sx={{ color: 'primary.main', marginRight: '12px', fontSize: '1.2rem' }} />
                    <ListItemText primary={item.text} />
                  </ListItemButton>
                </Link>
              )}

              {hasChildren && (
                <Collapse in={!!openGroup[item.path]} timeout="auto" unmountOnExit>
                  <List component="div" disablePadding>
                    {item.children!.map((child) => {
                      const ChildIcon = child.icon || IconComponent;
                      const childActive = location.pathname === child.path;
                      return (
                        <Link key={child.path} to={child.path} style={{ textDecoration: 'none', color: 'inherit' }}>
                          <ListItemButton
                            sx={{
                              pl: 6,
                              color: childActive ? '#FFF' : '#B9B9C2',
                              backgroundColor: childActive ? 'rgba(226,0,116,0.08)' : 'transparent',
                              borderLeft: childActive ? '4px solid' : '4px solid transparent',
                              borderLeftColor: childActive ? 'primary.main' : 'transparent',
                              fontWeight: childActive ? 600 : 'normal',
                              '&:hover': {
                                backgroundColor: 'rgba(255,255,255,0.04)',
                                color: '#FFF',
                              },
                              '& .MuiListItemText-primary': {
                                fontSize: '0.9rem',
                              },
                            }}
                            onClick={() => navigate(child.path)}
                          >
                            <ListItemIcon sx={{ minWidth: 32 }}>
                              <ChildIcon sx={{ color: 'primary.main', fontSize: '1.1rem' }} />
                            </ListItemIcon>
                            <ListItemText primary={child.text} />
                          </ListItemButton>
                        </Link>
                      );
                    })}
                  </List>
                </Collapse>
              )}
            </Box>
          );
        })}
      </List>
      <Box
        sx={{
          marginTop: 'auto',
          padding: '20px',
          fontSize: '0.75rem',
          opacity: 0.7,
        }}
      >
        © 2025 T-Systems
      </Box>
    </Box>
  );
};

export default Sidebar;