/**
 * 모바일 앱 UI 셸
 * - 햄버거 메뉴 + 드로어 네비게이션
 * - 하단 탭 바 (주요 화면)
 * - 터치 친화적 레이아웃
 */
import React, { useState } from 'react';
import {
  Box,
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Tooltip,
  Drawer,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  useTheme,
  BottomNavigation,
  BottomNavigationAction,
  Divider,
  Chip,
  Badge,
  Button,
  Menu,
  MenuItem,
  ListItemIcon as MenuItemIcon,
  ListItemText as MenuItemText,
} from '@mui/material';
import {
  Menu as MenuIcon,
  Analytics,
  Dashboard as DashboardIcon,
  GridView as MultiChartIcon,
  TrendingUp as TrendingUpIcon,
  ShowChart,
  Schedule,
  Settings as SettingsIcon,
  Notifications as NotificationsIcon,
  LightMode,
  DarkMode,
  Login as LoginIcon,
  Logout as LogoutIcon,
  AccountCircle,
  Person,
  Rule as RuleIcon,
  AccountBalance as SimulationIcon,
  CloudDownload,
  ListAlt as OrderbookIcon,
  AutoAwesome as AutoTradingIcon,
  FormatListBulleted as AlertListIcon,
  ClearAll as ClearAllIcon,
} from '@mui/icons-material';
import { useAppTheme } from '../contexts/ThemeContext';
import { useAuth } from '../contexts/AuthContext';
import { useAlertNotification } from '../contexts/AlertNotificationContext';
import { useNavigation } from '../contexts/NavigationContext';
import DashboardPage from '../pages/DashboardPage';
import PatternSearchPage from '../pages/PatternSearchPage';
import RisingStocksPage from '../pages/RisingStocksPage';
import StrategyTreeBuilderPage from '../pages/StrategyTreeBuilderPage';
import SimulationPage from '../pages/SimulationPage';
import DataCollectionPage from '../pages/DataCollectionPage';
import SchedulerPage from '../pages/SchedulerPage';
import SettingsPage from '../pages/SettingsPage';
import CandlestickTestPage from '../pages/CandlestickTestPage';
import AlertPage from '../pages/AlertPage';
import NotificationListPage from '../pages/NotificationListPage';
import OrderbookPage from '../pages/OrderbookPage';
import AutoTradingPage from '../pages/AutoTradingPage';
import MultiChartPage from '../pages/MultiChartPage';
import MultiChartPage2 from '../pages/MultiChartPage2';
import AlertListPage from '../pages/AlertListPage';
import MobileChartPage from '../pages/MobileChartPage';
import LoginDialog from './LoginDialog';
import SignUpDialog from './SignUpDialog';
import IndicatorConfigPanel from './IndicatorConfigPanel';
import IndicatorPopupWindow from './IndicatorPopupWindow';
import AlertSnackbar from './alert/AlertSnackbar';
import { useIndicatorPopup } from '../contexts/IndicatorPopupContext';

interface NavItem {
  page: string;
  label: string;
  icon: React.ReactNode;
}

const DRAWER_ITEMS: NavItem[] = [
  { page: 'dashboard', label: '대시보드', icon: <DashboardIcon /> },
  { page: 'multi-chart', label: '멀티차트', icon: <MultiChartIcon /> },
  { page: 'multi-chart-2', label: '멀티차트2', icon: <MultiChartIcon /> },
  { page: 'realtime-chart', label: '실시간 차트', icon: <TrendingUpIcon /> },
  { page: 'rising-stocks', label: '상승종목 추세', icon: <TrendingUpIcon /> },
  { page: 'pattern-search', label: '패턴검색', icon: <ShowChart /> },
  { page: 'simulation', label: '모의투자', icon: <SimulationIcon /> },
  { page: 'strategy-tree', label: '전략설정', icon: <RuleIcon /> },
  { page: 'candlestick-test', label: '투자분석', icon: <Analytics /> },
  { page: 'alerts', label: '알림 설정', icon: <NotificationsIcon /> },
  { page: 'alert-list', label: '알림목록', icon: <AlertListIcon /> },
  { page: 'orderbook', label: '실시간 호가', icon: <OrderbookIcon /> },
  { page: 'auto-trading', label: '자동매매', icon: <AutoTradingIcon /> },
  { page: 'data-collection', label: '데이터 수집', icon: <CloudDownload /> },
  { page: 'scheduler', label: '스케쥴러', icon: <Schedule /> },
  { page: 'settings', label: '설정', icon: <SettingsIcon /> },
];

const BOTTOM_NAV_ITEMS: NavItem[] = [
  { page: 'dashboard', label: '대시', icon: <DashboardIcon /> },
  { page: 'multi-chart', label: '멀티', icon: <MultiChartIcon /> },
  { page: 'candlestick-test', label: '분석', icon: <Analytics /> },
  { page: 'alerts', label: '알림', icon: <NotificationsIcon /> },
  { page: 'settings', label: '설정', icon: <SettingsIcon /> },
];

export const MobileAppShell: React.FC = () => {
  const theme = useTheme();
  const { currentPage, navigateToPage } = useNavigation();
  const { isPopupOpen, closePopup, chartData, chartMargin } = useIndicatorPopup();
  const { themeMode, setThemeMode } = useAppTheme();
  const { isAuthenticated, user, logout } = useAuth();
  const { unreadCount, notifications, dismissAllNotifications } = useAlertNotification();

  const [drawerOpen, setDrawerOpen] = useState(false);
  const [loginDialogOpen, setLoginDialogOpen] = useState(false);
  const [signUpDialogOpen, setSignUpDialogOpen] = useState(false);
  const [userMenuAnchor, setUserMenuAnchor] = useState<null | HTMLElement>(null);

  const handleThemeToggle = () => setThemeMode(themeMode === 'dark' ? 'light' : 'dark');
  const handleDrawerToggle = () => setDrawerOpen(!drawerOpen);
  const handleUserMenuOpen = (e: React.MouseEvent<HTMLElement>) => setUserMenuAnchor(e.currentTarget);
  const handleUserMenuClose = () => setUserMenuAnchor(null);
  const handleLogout = () => {
    logout();
    handleUserMenuClose();
  };

  const renderPage = () => {
    if (currentPage === 'candlestick-test' || currentPage === 'realtime-chart') {
      return <MobileChartPage embedded />;
    }
    switch (currentPage) {
      case 'dashboard':
        return <DashboardPage />;
      case 'multi-chart':
        return <MultiChartPage />;
      case 'multi-chart-2':
        return <MultiChartPage2 />;
      case 'rising-stocks':
        return <RisingStocksPage />;
      case 'pattern-search':
        return <PatternSearchPage />;
      case 'simulation':
        return <SimulationPage />;
      case 'strategy-tree':
        return <StrategyTreeBuilderPage />;
      case 'data-collection':
        return <DataCollectionPage />;
      case 'scheduler':
        return <SchedulerPage />;
      case 'alerts':
        return <AlertPage />;
      case 'alert-list':
        return <AlertListPage />;
      case 'notifications':
        return <NotificationListPage />;
      case 'orderbook':
        return <OrderbookPage />;
      case 'auto-trading':
        return <AutoTradingPage />;
      case 'settings':
        return <SettingsPage />;
      default:
        return <DashboardPage />;
    }
  };

  const bottomNavValue = BOTTOM_NAV_ITEMS.findIndex((i) => i.page === currentPage);
  const safeBottomNavValue = bottomNavValue >= 0 ? bottomNavValue : 0;

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        minHeight: '100dvh',
        bgcolor: 'background.default',
        pb: 'calc(56px + env(safe-area-inset-bottom, 0px))',
      }}
    >
      {/* 상단 앱바 (모바일 컴팩트) */}
      <AppBar
        position="fixed"
        elevation={0}
        sx={{
          bgcolor: themeMode === 'dark' ? 'background.paper' : 'primary.main',
          borderBottom: '1px solid',
          borderColor: 'divider',
          height: 56,
        }}
      >
        <Toolbar sx={{ minHeight: 56, px: 1, justifyContent: 'space-between' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <IconButton
              edge="start"
              color="inherit"
              onClick={handleDrawerToggle}
              sx={{ mr: 0.5 }}
              aria-label="메뉴"
            >
              <MenuIcon />
            </IconButton>
            <Analytics sx={{ fontSize: 24, color: themeMode === 'dark' ? 'primary.main' : '#fff' }} />
            <Typography
              variant="h6"
              component="div"
              sx={{
                fontSize: '1rem',
                fontWeight: 700,
                color: themeMode === 'dark' ? 'text.primary' : '#fff',
              }}
            >
              Golden
            </Typography>
          </Box>

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <IconButton size="small" onClick={handleThemeToggle} color="inherit">
              {themeMode === 'dark' ? <LightMode fontSize="small" /> : <DarkMode fontSize="small" />}
            </IconButton>
            <Tooltip title="알림팝업 전체 닫기">
              <span>
                <IconButton
                  size="small"
                  onClick={dismissAllNotifications}
                  disabled={notifications.length === 0}
                  color="inherit"
                  aria-label="알림팝업 전체 닫기"
                >
                  <ClearAllIcon fontSize="small" />
                </IconButton>
              </span>
            </Tooltip>
            {isAuthenticated ? (
              <IconButton size="small" onClick={handleUserMenuOpen} color="inherit">
                <AccountCircle />
              </IconButton>
            ) : (
              <Button
                size="small"
                variant="outlined"
                startIcon={<LoginIcon />}
                onClick={() => setLoginDialogOpen(true)}
                sx={{
                  borderColor: themeMode === 'dark' ? 'primary.main' : '#fff',
                  color: themeMode === 'dark' ? 'primary.main' : '#fff',
                  fontSize: '0.75rem',
                  py: 0.25,
                }}
              >
                로그인
              </Button>
            )}
          </Box>
        </Toolbar>
      </AppBar>

      {/* 네비게이션 드로어 */}
      <Drawer
        variant="temporary"
        open={drawerOpen}
        onClose={handleDrawerToggle}
        ModalProps={{ keepMounted: true }}
        sx={{
          '& .MuiDrawer-paper': {
            width: 280,
            boxSizing: 'border-box',
            mt: 0,
            pt: 1,
          },
        }}
      >
        <Box sx={{ px: 2, py: 1 }}>
          <Typography variant="subtitle1" fontWeight={700} color="text.primary">
            Golden Analysis
          </Typography>
          <Typography variant="caption" color="text.secondary">
            투자전략 성능 분석
          </Typography>
        </Box>
        <Divider />
        <List sx={{ pt: 0 }}>
          {DRAWER_ITEMS.map((item) => (
            <ListItem
              key={item.page}
              button
              onClick={() => {
                navigateToPage(item.page);
                setDrawerOpen(false);
              }}
              selected={currentPage === item.page}
              sx={{
                py: 1.25,
                '&.Mui-selected': {
                  bgcolor: 'action.selected',
                },
              }}
            >
              <ListItemIcon sx={{ minWidth: 40 }}>{item.icon}</ListItemIcon>
              <ListItemText
                primary={item.label}
                primaryTypographyProps={{ fontSize: '0.9rem' }}
              />
              {item.page === 'alerts' && unreadCount > 0 && (
                <Chip
                  label={unreadCount}
                  size="small"
                  color="error"
                  sx={{ height: 20, fontSize: '0.7rem' }}
                />
              )}
            </ListItem>
          ))}
        </List>
      </Drawer>

      {/* 메인 콘텐츠 (모바일 터치 최적화) */}
      <Box
        component="main"
        sx={{
          flex: 1,
          mt: '56px',
          minHeight: 'calc(100dvh - 56px - 56px)',
          overflow: (currentPage === 'candlestick-test' || currentPage === 'realtime-chart') ? 'hidden' : 'auto',
          overflowX: 'hidden',
          WebkitOverflowScrolling: 'touch',
          touchAction: 'pan-y',
          px: (currentPage === 'candlestick-test' || currentPage === 'realtime-chart') ? 0 : 1.5,
          py: (currentPage === 'candlestick-test' || currentPage === 'realtime-chart') ? 0 : 1.5,
          maxWidth: '100%',
          display: 'flex',
          flexDirection: 'column',
          height: (currentPage === 'candlestick-test' || currentPage === 'realtime-chart')
            ? 'calc(100dvh - 56px - 56px)'
            : undefined,
        }}
      >
        {renderPage()}
      </Box>

      {/* 하단 네비게이션 (safe-area 지원) */}
      <BottomNavigation
        value={safeBottomNavValue}
        onChange={(_, newValue) => {
          const item = BOTTOM_NAV_ITEMS[newValue];
          if (item) navigateToPage(item.page);
        }}
        showLabels
        sx={{
          position: 'fixed',
          bottom: 0,
          left: 0,
          right: 0,
          height: 'calc(56px + env(safe-area-inset-bottom, 0px))',
          paddingBottom: 'env(safe-area-inset-bottom, 0px)',
          bgcolor: 'background.paper',
          borderTop: '1px solid',
          borderColor: 'divider',
          '& .MuiBottomNavigationAction-label': {
            fontSize: '0.7rem',
          },
        }}
      >
        {BOTTOM_NAV_ITEMS.map((item, idx) => (
          <BottomNavigationAction
            key={item.page}
            label={item.label}
            icon={
              item.page === 'alerts' && unreadCount > 0 ? (
                <Badge badgeContent={unreadCount} color="error">
                  {item.icon}
                </Badge>
              ) : (
                item.icon
              )
            }
          />
        ))}
      </BottomNavigation>

      {/* 사용자 메뉴 */}
      <Menu
        anchorEl={userMenuAnchor}
        open={Boolean(userMenuAnchor)}
        onClose={handleUserMenuClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        <MenuItem disabled>
          <MenuItemIcon>
            <Person fontSize="small" />
          </MenuItemIcon>
          <MenuItemText primary={user?.username} secondary={user?.email} />
        </MenuItem>
        <Divider />
        <MenuItem onClick={handleLogout}>
          <MenuItemIcon>
            <LogoutIcon fontSize="small" />
          </MenuItemIcon>
          <MenuItemText primary="로그아웃" />
        </MenuItem>
      </Menu>

      <LoginDialog
        open={loginDialogOpen}
        onClose={() => setLoginDialogOpen(false)}
        onSwitchToSignUp={() => {
          setLoginDialogOpen(false);
          setSignUpDialogOpen(true);
        }}
      />
      <SignUpDialog
        open={signUpDialogOpen}
        onClose={() => setSignUpDialogOpen(false)}
        onSwitchToLogin={() => {
          setSignUpDialogOpen(false);
          setLoginDialogOpen(true);
        }}
      />
      <IndicatorConfigPanel />
      <IndicatorPopupWindow
        open={isPopupOpen}
        onClose={closePopup}
        chartData={chartData}
        chartMargin={chartMargin}
      />
      <AlertSnackbar />
    </Box>
  );
};
