import { Link as RouterLink, useNavigate } from 'react-router';

import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import HelpIcon from '@mui/icons-material/HelpOutlineOutlined';
import { Box, FormControlLabel, Link, svgIconClasses, Tab, Tabs, Tooltip, Typography } from '@mui/material';

import { CheckSwitch } from '../../common/CheckSwitch';
import { EditableField } from '../../common/EditableField';
import { useGroupsConfig } from '../GroupsConfigContext';
import { MAX_NAME_LENGTH } from '../constants';
import { useAppDispatch } from '../store';
import { makePersonal, makeShared, saveGroupTitle } from '../store/groupDetailSlice/thunks';
import type { Group, GroupType } from '../types';

interface GroupHeaderProps {
  group: Group;
  tab: 'overview' | 'data' | 'modules';
  type: GroupType;
}

const breadcrumbSx = {
  alignItems: 'center',
  color: 'text.primary',
  display: 'inline-flex',
  [`& .${svgIconClasses.root}`]: { mr: '16px' }
} as const;

export const GroupHeader = ({ group, type, tab }: GroupHeaderProps) => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const { canCreateShared, isSuperHub } = useGroupsConfig();
  const shared = type === 'shared';
  const id = String(group.id);

  const toggleShared = () => {
    if (shared) {
      dispatch(makePersonal(id))
        .unwrap()
        .then(newId => navigate(`/personal/${newId}`))
        .catch(() => undefined);
    } else {
      dispatch(makeShared(id))
        .unwrap()
        .then(newId => navigate(`/shared/${newId}`))
        .catch(() => undefined);
    }
  };

  return (
    <Box>
      <Link component={RouterLink} to={shared ? '/shared' : '/'} variant="subtitle1" sx={breadcrumbSx}>
        <ChevronLeftIcon fontSize="small" />
        {shared ? 'Shared groups' : 'My groups'}
      </Link>

      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mt: 1, flexWrap: 'wrap', gap: 1 }}>
        <Typography variant="h1" sx={{ m: '40px 0' }}>
          <EditableField value={group.name} maxLength={MAX_NAME_LENGTH} onSave={name => dispatch(saveGroupTitle({ id, type, name })).unwrap()} />
        </Typography>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          {!canCreateShared && (
            <Tooltip title="You don't have access to create shared groups, ask an administrator for assistance.">
              <HelpIcon fontSize="small" color="action" />
            </Tooltip>
          )}
          <FormControlLabel
            label="Shared group"
            labelPlacement="start"
            sx={{ gap: 2 }}
            control={<CheckSwitch checked={shared} disabled={!shared && !canCreateShared} onChange={toggleShared} />}
          />
        </Box>
      </Box>

      <Tabs value={tab} sx={{ mt: 1, borderBottom: 1, borderColor: 'divider' }}>
        <Tab label="Overview" value="overview" component={RouterLink} to={`/${type}/${id}`} />
        {/* Data & Modules tabs are hidden on super-hub setups. */}
        {!isSuperHub && <Tab label="Data" value="data" component={RouterLink} to={`/${type}/${id}/data`} />}
        {!isSuperHub && <Tab label="Modules" value="modules" component={RouterLink} to={`/${type}/${id}/modules`} />}
      </Tabs>
    </Box>
  );
};
