import {
  Box,
  Button,
  Tab,
  Tabs,
  Typography,
  Menu,
  MenuItem,
  Divider,
} from '@mui/material';
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
import { useLocation, useNavigate } from 'react-router-dom';
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import { useEffect, useRef, useState, useCallback } from 'react';
import CustomTooltip from './Notifications/CustomTooltip';
import CoinsDisplay from './CoinsDisplay';
import { HeadAvatar } from './HeadAvatar';
import { fetchPlayer } from './../api';
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import EmojiEventsIcon from '@mui/icons-material/EmojiEvents';
import PersonIcon from '@mui/icons-material/Person';
import SettingsIcon from '@mui/icons-material/Settings';
declare global {
  interface Window {
    electron: {
      ipcRenderer: {
        invoke(channel: string, ...args: unknown[]): Promise<any>;
        on(channel: string, func: (...args: unknown[]) => void): void;
        removeAllListeners(channel: string): void;
      };
    };
  }
}

// Определяем пропсы
interface TopBarProps {
  onRegister?: () => void; // Опционально, если нужен обработчик регистрации
  username?: string;
}

export default function TopBar({ onRegister, username }: TopBarProps) {
  // Получаем текущий путь
  const location = useLocation();
  const isLoginPage = location.pathname === '/login';
  const [isAuthed, setIsAuthed] = useState(false);
  const isLaunchPage = location.pathname.startsWith('/launch');
  const isRegistrationPage = location.pathname === '/registration';
  const navigate = useNavigate();
  const tabsWrapperRef = useRef<HTMLDivElement | null>(null);
  const tabsRootRef = useRef<HTMLDivElement | null>(null);

  const updateGradientVars = useCallback(() => {
    const root = tabsRootRef.current;
    if (!root) return;

    const tabsRect = root.getBoundingClientRect();
    const active = root.querySelector<HTMLElement>('.MuiTab-root.Mui-selected');
    if (!active) return;

    const activeRect = active.getBoundingClientRect();
    const x = activeRect.left - tabsRect.left;

    root.style.setProperty('--tabs-w', `${tabsRect.width}px`);
    root.style.setProperty('--active-x', `${x}px`);
  }, []);

  const [skinUrl, setSkinUrl] = useState<string>('');
  const [skinVersion, setSkinVersion] = useState(0);
  const [avatarAnchorEl, setAvatarAnchorEl] = useState<null | HTMLElement>(
    null,
  );

  const path = location.pathname || '';
  const isAuthPage = path.startsWith('/login') || path.startsWith('/registration');

  const TAB_ROUTES: Array<{
    value: number;
    match: (p: string) => boolean;
    to: string;
  }> = [
    {
      value: 0,
      match: (p) => p === '/news',
      to: '/news',
    },
    {
      value: 1,
      match: (p) => p === '/',
      to: '/',
    },
    {
      value: 2,
      match: (p) => p.startsWith('/shop'),
      to: '/shop',
    },
    {
      value: 3,
      match: (p) => p.startsWith('/marketplace'),
      to: '/marketplace',
    },
  ];

  const selectedTab =
    TAB_ROUTES.find((r) => r.match(location.pathname))?.value ?? false;

  useEffect(() => {
    updateGradientVars();
    window.addEventListener('resize', updateGradientVars);
    return () => window.removeEventListener('resize', updateGradientVars);
  }, [updateGradientVars, selectedTab, location.pathname]);

  useEffect(() => {
    const saved = localStorage.getItem('launcher_config');
    try {
      const cfg = saved ? JSON.parse(saved) : null;
      setIsAuthed(Boolean(cfg?.accessToken)); // или cfg?.uuid/username — как у тебя принято
    } catch {
      setIsAuthed(false);
    }
  }, [location.pathname]); // можно и без dependency, но так надёжнее при logout/login

  const avatarMenuOpen = Boolean(avatarAnchorEl);

  const handleAvatarClick = (event: React.MouseEvent<HTMLElement>) => {
    setAvatarAnchorEl(event.currentTarget);
  };

  const handleAvatarMenuClose = () => {
    setAvatarAnchorEl(null);
  };

  // useEffect(() => {
  //   if (location.pathname === '/news') {
  //     setValue(0);
  //     setActivePage('news');
  //   } else if (location.pathname === '/') {
  //     setValue(1);
  //     setActivePage('versions');
  //   } else if (location.pathname.startsWith('/shop')) {
  //     setValue(3);
  //     setActivePage('shop');
  //   } else if (location.pathname.startsWith('/marketplace')) {
  //     setValue(4);
  //     setActivePage('marketplace');
  //   } else {
  //     // любые страницы не из TopBar: /profile, /daily, /dailyquests, и т.д.
  //     setValue(false);
  //     setActivePage('');
  //   }
  // }, [location.pathname]);

  const handleLaunchPage = () => {
    navigate('/');
  };

  const handleTabsWheel = (event: React.WheelEvent<HTMLDivElement>) => {
    // чтобы страница не скроллилась вертикально
    event.preventDefault();

    if (!tabsWrapperRef.current) return;

    // Находим внутренний скроллер MUI Tabs
    const scroller = tabsWrapperRef.current.querySelector(
      '.MuiTabs-scroller',
    ) as HTMLDivElement | null;

    if (!scroller) return;

    // Прокручиваем горизонтально, используя вертикальный скролл мыши
    scroller.scrollLeft += event.deltaY * 0.3;

    requestAnimationFrame(updateGradientVars);
  };

  // const getPageTitle = () => {
  //   if (isLoginPage) {
  //     return 'Вход';
  //   }
  //   if (isLaunchPage) {
  //     return 'Запуск';
  //   }
  //   if (isVersionsExplorerPage) {
  //     if (activePage === 'versions') {
  //       return 'Версии';
  //     }
  //     if (activePage === 'profile') {
  //       return 'Профиль';
  //     }
  //     if (activePage === 'shop') {
  //       return 'Магазин';
  //     }
  //     if (activePage === 'marketplace') {
  //       return 'Рынок';
  //     }
  //   }
  //   return 'Неизвестная страница';
  // };

  // Функция для получения количества монет

  const tabBaseSx = {
    color: 'white',
    fontFamily: 'Benzin-Bold',
    fontSize: '0.7em',
    transition: 'all 0.3s ease',
    '&:hover': {
      color: 'rgb(170, 170, 170)',
    },
  };

  const activeTabSx = {
    color: 'transparent',
    WebkitTextFillColor: 'transparent',
    backgroundImage: 'var(--tabs-grad)',
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'var(--tabs-w) 100%',
    backgroundPosition: 'calc(-1 * var(--active-x)) 0',
    WebkitBackgroundClip: 'text',
    backgroundClip: 'text',
  };

  const logout = () => {
    localStorage.removeItem('launcher_config');
    navigate('/login');
  };

  const loadSkin = useCallback(async () => {
    if (!isAuthed) {
      setSkinUrl('');
      return;
    }

  const savedConfig = localStorage.getItem('launcher_config');
    if (!savedConfig) return;

    let cfg: any = null;
    try {
      cfg = JSON.parse(savedConfig);
    } catch {
      return;
    }

    const uuid = cfg?.uuid;
    if (!uuid) return;

    try {
      const player = await fetchPlayer(uuid);
      setSkinUrl(player.skin_url || '');
    } catch (e) {
      console.error('Не удалось получить скин:', e);
      setSkinUrl('');
    }
  }, [isAuthed]);

  useEffect(() => {
    loadSkin();
  }, [loadSkin, location.pathname]);

  useEffect(() => {
    const handler = () => {
      setSkinVersion((v) => v + 1);
      loadSkin();
    };

    window.addEventListener('skin-updated', handler as EventListener);
    return () => window.removeEventListener('skin-updated', handler as EventListener);
  }, [loadSkin]);

  return (
    <Box
      sx={{
        display: 'flex',
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        height: '8vh',
        zIndex: 1000,
        width: '100%',
        WebkitAppRegion: 'drag',
        overflow: 'hidden',
        justifyContent: 'space-between',
        alignItems: 'center',

        // убрать если не оч

        // стиль как в Registration
        background: isAuthPage ?
          'none' : 'linear-gradient(71deg, rgba(242,113,33,0.18) 0%, rgba(233,64,205,0.14) 70%, rgba(138,35,135,0.16) 100%)',
        backdropFilter: isAuthPage ? 'none' : 'blur(10px)',
        boxShadow: isAuthPage ? 'none' : '0 8px 30px rgba(0,0,0,0.35)',
      }}
    >
      {/* Левая часть */}
      <Box
        sx={{
          display: 'flex',
          WebkitAppRegion: 'no-drag',
          gap: '2vw',
          alignItems: 'center',
          marginLeft: '1vw',
        }}
      >
        {(isLaunchPage || isRegistrationPage) && (
          <Button
            variant="outlined"
            onClick={() => handleLaunchPage()}
            sx={{
              width: '3em',
              height: '3em',
              borderRadius: '50%',
              border: 'unset',
              color: 'white',
              minWidth: 'unset',
              minHeight: 'unset',
              transition: 'transform 0.3s ease',
              '&:hover': {
                transform: 'scale(1.2)',
              },
            }}
          >
            <ArrowBackRoundedIcon />
          </Button>
        )}
        {isAuthed && !isLaunchPage && (
          <Box
            ref={tabsWrapperRef}
            onWheel={handleTabsWheel}
            // старый вариант
            sx={{
              borderBottom: 1,
              borderColor: 'transparent',
              // '& .MuiTabs-indicator': {
              //   backgroundColor: 'rgba(255, 77, 77, 1)',
              // },
            }}
            // sx={{
            //   borderBottom: 'none',
            //   borderRadius: '2vw',
            //   px: '0.6vw',
            //   py: '0.4vw',
            //   background: 'rgba(0,0,0,0.35)',
            //   border: '1px solid rgba(255,255,255,0.08)',
            //   boxShadow: '0 8px 20px rgba(0,0,0,0.25)',
            //   '& .MuiTabs-indicator': {
            //     height: '100%',
            //     borderRadius: '1.6vw',
            //     background:
            //       'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
            //     opacity: 0.18,
            //   },
            // }}
          >
            <CustomTooltip
              title={
                'Покрути колесиком мыши чтобы увидеть остальные элементы меню'
              }
              arrow
              placement="bottom"
              TransitionProps={{ timeout: 100 }}
            >
              <Tabs
                ref={tabsRootRef}
                value={selectedTab}
                onChange={(_, newValue) => {
                  const route = TAB_ROUTES.find((r) => r.value === newValue);
                  if (route) navigate(route.to);
                }}
                aria-label="basic tabs example"
                variant="scrollable"
                scrollButtons={false}
                disableRipple={true}
                sx={{
                  // один градиент на весь Tabs
                  '--tabs-grad': 'linear-gradient(90deg, #F27121 0%, #E940CD 50%, #8A2387 100%)',

                  // активный текст показывает “срез” общего градиента
                  '& .MuiTab-root.Mui-selected': {
                    color: 'transparent',
                    backgroundImage: 'var(--tabs-grad)',
                    backgroundRepeat: 'no-repeat',
                    backgroundSize: 'var(--tabs-w) 100%',
                    backgroundPosition: 'calc(-1 * var(--active-x)) 0',
                    WebkitBackgroundClip: 'text',
                    backgroundClip: 'text',
                  },

                  // подчёркивание тоже из того же “единого” градиента
                  '& .MuiTabs-indicator': {
                    height: '2px',
                    backgroundImage: 'var(--tabs-grad)',
                    backgroundRepeat: 'no-repeat',
                    backgroundSize: 'var(--tabs-w) 100%',
                    backgroundPosition: 'calc(-1 * var(--active-x)) 0',
                  },
                }}
              >
                <Tab
                  label="Новости"
                  disableRipple={true}
                  sx={{
                    ...tabBaseSx,
                    ...(selectedTab === 0 ? activeTabSx : null),
                  }}
                />
                <Tab
                  label="Версии"
                  disableRipple={true}
                  sx={{
                    ...tabBaseSx,
                    ...(selectedTab === 1 ? activeTabSx : null),
                  }}
                />
                <Tab
                  label="Магазин"
                  disableRipple={true}
                  sx={{
                    ...tabBaseSx,
                    ...(selectedTab === 2 ? activeTabSx : null),
                  }}
                />
                <Tab
                  label="Рынок"
                  disableRipple={true}
                  sx={{
                    ...tabBaseSx,
                    ...(selectedTab === 3 ? activeTabSx : null),
                  }}
                />
              </Tabs>
            </CustomTooltip>
          </Box>
        )}
      </Box>
      {/* Центр */}
      <Box
        sx={{
          position: 'absolute',
          left: '50%',
          transform: 'translateX(-50%)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          flexGrow: 1,
          WebkitAppRegion: 'drag',
        }}
      >
        {/* <Typography
          variant="h6"
          sx={{ color: 'white', fontFamily: 'Benzin-Bold' }}
        >
          {getPageTitle()}
        </Typography> */}
      </Box>
      {/* Правая часть со всеми кнопками */}
      <Box
        sx={{
          display: 'flex',
          WebkitAppRegion: 'no-drag',
          gap: '1vw',
          alignItems: 'center',
          marginRight: '1vw',
        }}
      >
        {!isLoginPage && !isRegistrationPage && username && (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: '1vw' }}>
            <HeadAvatar
              skinUrl={skinUrl}
              size={44}
              version={skinVersion}
              style={{
                borderRadius: '3vw',
                cursor: 'pointer',
              }}
              onClick={handleAvatarClick}
            />
          </Box>
        )}
        {/* Кнопка регистрации, если на странице логина */}
        {!isLoginPage && !isRegistrationPage && username && (
          <CoinsDisplay
            username={username}
            size="medium"
            autoUpdate={true}
            showTooltip={true}
          />
        )}

        {/* Кнопки управления окном */}
        <Button
          onClick={() => {
            window.electron.ipcRenderer.invoke('minimize-app');
          }}
          sx={{
            minWidth: 'unset',
            minHeight: 'unset',
            width: '3em',
            height: '3em',
            borderRadius: '50%',
          }}
        >
          <svg
            className="MuiSvgIcon-root MuiSvgIcon-fontSizeMedium"
            focusable="false"
            aria-hidden="true"
            viewBox="0 0 24 24"
          >
            <path
              d="M 7 19 h 10 c 0.55 0 1 0.45 1 1 s -0.45 1 -1 1 H 7 c -0.55 0 -1 -0.45 -1 -1 s 0.45 -1 1 -1"
              fill="white"
            ></path>
          </svg>
        </Button>
        <Button
          onClick={() => {
            window.electron.ipcRenderer.invoke('close-app');
          }}
          sx={{
            minWidth: 'unset',
            minHeight: 'unset',
            width: '3em',
            height: '3em',
            borderRadius: '50%',
          }}
        >
          <CloseRoundedIcon sx={{ color: 'white' }} />
        </Button>
      </Box>
      <Menu
        anchorEl={avatarAnchorEl}
        open={avatarMenuOpen}
        onClose={handleAvatarMenuClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        PaperProps={{
          sx: {
            mt: '0.5vw',
            borderRadius: '1vw',
            minWidth: '16vw',
            color: 'white',
            bgcolor: 'rgba(0,0,0,0.82)',
            backdropFilter: 'blur(10px)',
            border: '1px solid rgba(233,64,205,0.25)',
            boxShadow: '0 18px 40px rgba(0,0,0,0.55)',
          },
        }}
      >
        {/* ===== 1 строка: аватар + ник + валюта ===== */}
        <Box
          sx={{
            display: 'grid',
            gridTemplateColumns: 'auto 1fr',
            gap: '1.5vw',
            alignItems: 'center',
            px: '2vw',
            py: '0.8vw',
          }}
        >
          <HeadAvatar
            skinUrl={skinUrl}
            size={40}
            version={skinVersion}
            style={{ borderRadius: '3vw' }}
          />

          <Box sx={{ display: 'flex', flexDirection: 'column' }}>
            <Typography
              sx={{
                fontFamily: 'Benzin-Bold',
                fontSize: '2vw',
              }}
            >
              {username || 'Игрок'}
            </Typography>

            <CoinsDisplay
              username={username}
              size="medium"
              autoUpdate={true}
              showTooltip={false}
              sx={{
                border: 'none',
                padding: '0vw',
              }}
              backgroundColor={'rgba(0, 0, 0, 0)'}
            />
          </Box>
        </Box>

        <Divider sx={{ my: '0.4vw', borderColor: 'rgba(255,255,255,0.08)' }} />

        <MenuItem
          onClick={() => {
            handleAvatarMenuClose();
            navigate('/profile');
          }}
          sx={{
            fontFamily: 'Benzin-Bold',
            fontSize: '1.5vw',
            gap: '0.5vw',
            py: '0.7vw',
            '&:hover': {
              bgcolor: 'rgba(255,77,77,0.15)',
            },
          }}
        >
          <PersonIcon sx={{ fontSize: '2vw' }} /> Профиль
        </MenuItem>

        {/* ===== 2 строка: ежедневные задания ===== */}
        <MenuItem
          onClick={() => {
            handleAvatarMenuClose();
            navigate('/dailyquests');
          }}
          sx={{
            fontFamily: 'Benzin-Bold',
            fontSize: '1.5vw',
            gap: '0.5vw',
            py: '0.7vw',
            '&:hover': {
              bgcolor: 'rgba(255,77,77,0.15)',
            },
          }}
        >
          <CalendarMonthIcon sx={{ fontSize: '2vw' }} /> Ежедневные задания
        </MenuItem>

        {/* ===== 3 строка: ежедневная награда ===== */}
        <MenuItem
          onClick={() => {
            handleAvatarMenuClose();
            navigate('/daily');
          }}
          sx={{
            fontFamily: 'Benzin-Bold',
            fontSize: '1.5vw',
            gap: '0.5vw',
            py: '0.7vw',
            '&:hover': {
              bgcolor: 'rgba(255,77,77,0.15)',
            },
          }}
        >
          <EmojiEventsIcon sx={{ fontSize: '2vw' }} /> Ежедневная награда
        </MenuItem>

        <MenuItem
          onClick={() => {
            handleAvatarMenuClose();
            navigate('/settings');
          }}
          sx={{
            fontFamily: 'Benzin-Bold',
            fontSize: '1.5vw',
            gap: '0.5vw',
            py: '0.7vw',
            '&:hover': {
              bgcolor: 'rgba(255,77,77,0.15)',
            },
          }}
        >
          <SettingsIcon sx={{ fontSize: '2vw' }} /> Настройки
        </MenuItem>

        <Divider sx={{ my: '0.4vw', borderColor: 'rgba(255,255,255,0.08)' }} />
        {!isLoginPage && !isRegistrationPage && username && (
          <Button
            variant="outlined"
            color="primary"
            onClick={() => {
              handleAvatarMenuClose();
              logout();
            }}
            sx={{
              width: '8vw',
              height: '3vw',
              borderRadius: '2.5vw',
              fontFamily: 'Benzin-Bold',
              fontSize: '1.2vw',
              background:
                'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
              color: 'white',
              border: 'none',
              transition: 'transform 0.3s ease',
              '&:hover': {
                background:
                  'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
                transform: 'scale(1.01)',
                boxShadow: '0 4px 15px rgba(242, 113, 33, 0.4)',
              },
              boxShadow: '0 2px 8px rgba(0, 0, 0, 0.3)',
              m: '0 0 0 18vw',
            }}
          >
            Выйти
          </Button>
        )}

        {/* ↓↓↓ дальше ты сам добавишь пункты ↓↓↓ */}
      </Menu>
    </Box>
  );
}
