import { useState } from 'react';
import { useQuery } from 'react-query';

import CardContent from '@material-hu/mui/CardContent';
import CardHeader from '@material-hu/mui/CardHeader';
import Divider from '@material-hu/mui/Divider';
import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';
import { styled } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import usePermissions from 'src/hooks/usePermissions';
import ArrowLeft from 'src/icons/ArrowLeft';
import ArrowRight from 'src/icons/ArrowRight';
import { getWidgetList } from 'src/services/widgets';
import { IconTypes } from 'src/types/icons';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullLink } from 'src/utils/links';
import { UserPermissions } from 'src/utils/permissions';
import { getActiveUrls } from 'src/utils/widgets';

import { widgetKeys } from 'src/components/dashboard/widgets/queries';
import WidgetIcon from 'src/components/dashboard/widgets/WidgetIcon';

const MAX_LINKS = 10;

const Card = styled(HuCardContainer)(({ theme }) => ({
  height: 'fit-content',
  width: '400px',
  '& .MuiCardContent-root': {
    padding: theme.spacing(0),
  },
  '& .MuiCardContent-root:last-child': {
    padding: 0,
  },
  '& .MuiBox-root.scrollbar-container': {
    position: 'relative',
    zIndex: 0,
  },
}));

const { VIEW_WIDGET } = UserPermissions;

const WidgetsCard = () => {
  const [showAll, setShowAll] = useState(false);

  const { t } = useLokaliseTranslation('dashboard_sidebar_app');
  const { hasAll: canViewWidgets } = usePermissions([VIEW_WIDGET]);

  const { data } = useQuery(widgetKeys.list(), getWidgetList, {
    enabled: !!canViewWidgets,
  });

  const handleOnClick = () => setShowAll(!showAll);

  const links = getActiveUrls(data?.data);

  const displayLimit = showAll ? links.length : MAX_LINKS;

  return (
    links &&
    links.length > 0 &&
    canViewWidgets && (
      <Card sx={{ pb: 1 }}>
        <CardHeader
          title={
            <Typography
              variant="globalM"
              fontWeight="semiBold"
            >
              {t('widgets')}
            </Typography>
          }
          sx={{ pb: 1 }}
        />
        <CardContent>
          <Stack
            sx={{
              flexDirection: 'row',
              flexWrap: 'wrap',
              p: 1,
              px: 2,
              gap: 1.4,
            }}
          >
            {links?.slice(0, displayLimit).map(widget => (
              <HuTooltip
                key={widget.id}
                title={widget.title}
                direction="bottom"
              >
                <Button
                  component={Link}
                  href={getFullLink({ link: widget.body })}
                  target="_blank"
                  rel="noreferrer"
                  aria-label={widget.title}
                  sx={theme => ({
                    bgcolor: theme.palette.new.background.layout.default,
                    minWidth: '64px',
                    minHeight: '64px',
                    maxWidth: '64px',
                    maxHeight: '64px',
                    borderRadius: '50%',
                    padding: '12px',
                    overflow: 'hidden',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  })}
                >
                  <WidgetIcon
                    icon={widget.icon}
                    width={
                      widget.icon.type === IconTypes.IMAGE ? '100%' : '40px'
                    }
                    height={
                      widget.icon.type === IconTypes.IMAGE ? '100%' : '40px'
                    }
                    objectFit="contain"
                  />
                </Button>
              </HuTooltip>
            ))}
          </Stack>
          {links.length > MAX_LINKS && (
            <>
              <Divider sx={{ mt: 1 }} />
              <Stack
                sx={{
                  pt: 1,
                  flexDirection: 'row',
                  width: '100%',
                  justifyContent: 'flex-end',
                  px: 2,
                }}
              >
                <Button
                  variant="text"
                  onClick={handleOnClick}
                  endIcon={showAll ? undefined : <ArrowRight />}
                  startIcon={showAll ? <ArrowLeft /> : undefined}
                >
                  <Typography
                    variant="globalXS"
                    fontWeight="semiBold"
                    sx={theme => ({
                      color: theme.palette.new.text.neutral.brand,
                    })}
                  >
                    {showAll ? t('general:show_less') : t('general:show_more')}
                  </Typography>
                </Button>
              </Stack>
            </>
          )}
        </CardContent>
      </Card>
    )
  );
};

export default WidgetsCard;
