import { isValidElement, useEffect } from 'react';
import { Box, Stack, Typography, useMediaQuery, SxProps, Theme } from '@mui/material';
import Tabs from '@arcblock/ux/lib/Tabs';
import AppBadge from './app-badge';
import { useAppInfo } from './app-info-context';

function useMobile(): boolean {
  const isMobile = useMediaQuery((theme: Theme) => theme.breakpoints.down('md'));

  return isMobile;
}

interface DividerProps {
  sx?: SxProps<Theme>;
}

function Divider({ sx = {} }: DividerProps) {
  const isMobile = useMobile();

  return (
    <Box sx={{ mx: isMobile ? -2 : -3, borderBottom: '1px solid', borderColor: 'divider', mt: 1.5, mb: 1, ...sx }} />
  );
}

interface AppHeaderProps {
  onTabChange?: (tab: string) => void;
}

function AppHeader({ onTabChange = undefined }: AppHeaderProps) {
  const isMobile = useMobile();
  const {
    inService,
    navItem,
    icon = undefined,
    name = '',
    description = undefined,
    actions = undefined,
    badges = [],
    tabs = [],
    currentTab = '',
    updateAppInfo,
  } = useAppInfo();

  // 非 Service 应用，自动更新 name / description
  useEffect(() => {
    if (!inService) {
      updateAppInfo({
        name: navItem?.title || '',
        description: navItem?.description || '',
      });
    }
  }, [navItem?.title, navItem?.description, inService, updateAppInfo]);

  if (!name) {
    return null;
  }

  return (
    <Box className="app-header" sx={{ mt: 3, mb: 3 }}>
      {/* Basic Info */}
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          gap: 1,
        }}>
        {icon && <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{icon}</Box>}
        <Stack sx={{ flexGrow: 1 }}>
          <Typography variant="h1" sx={{ mb: 0.5 }}>
            {name}
          </Typography>
          {description && (
            <Typography
              variant="body2"
              color="text.secondary"
              sx={{ lineHeight: 1.6, '& a': { color: 'primary.main' }, maxWidth: 980 }}>
              {description}
            </Typography>
          )}
        </Stack>
        {!isMobile && actions && <Box sx={{ ml: 1 }}>{actions}</Box>}
      </Box>
      {/* Badges */}
      {badges.length > 0 && (
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, alignItems: 'center', mt: 2 }}>
          {badges.map((config, index) =>
            isValidElement(config) ? config : <AppBadge key={config.label || index} {...config} />
          )}
        </Box>
      )}
      {isMobile && actions && <Box sx={{ mt: isMobile ? 2 : 0 }}>{actions}</Box>}
      {/* Tabs */}
      {tabs.length <= 1 && <Divider />}
      {tabs.length > 1 && (
        <>
          <Tabs tabs={tabs} current={currentTab} onChange={onTabChange} scrollButtons="auto" sx={{ mt: 2.5 }} />
          <Divider sx={{ mt: 0 }} />
        </>
      )}
    </Box>
  );
}

export default AppHeader;
