import { type FC, memo, useState } from 'react';
import { useMutation, 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 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 { getIdpProviders, initIdpLogin } from 'src/services/authService';
import { IconTypes } from 'src/types/icons';
import { IDP_PROVIDER_PROTOCOL, type IdpProvider } from 'src/types/login';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';

import WidgetIcon from 'src/components/dashboard/widgets/WidgetIcon';

import { launchIdpProvider } from './launchIdpProvider';
import { externalToolsKeys } from './queries';

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_EXTERNAL_APPS } = UserPermissions;

export const ExternalToolsCard: FC = memo(
  function ExternalToolsCardComponent() {
    const [showAll, setShowAll] = useState(false);

    const { t } = useLokaliseTranslation('authentication');
    const { hasAll: canViewExternalApps } = usePermissions([
      VIEW_EXTERNAL_APPS,
    ]);

    const { data: appsData } = useQuery(
      externalToolsKeys.list(),
      getIdpProviders,
      {
        select: r => r.data,
        enabled: !!canViewExternalApps,
      },
    );

    const samlMutation = useMutation((id: number) => initIdpLogin(id), {
      onSuccess: ({ data }) => {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = data.acsUrl;
        form.target = '_blank';

        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'SAMLResponse';
        input.value = data.SAMLResponse;
        form.appendChild(input);

        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
      },
    });

    const oauthMutation = useMutation(launchIdpProvider);

    const handleAppClick = (app: IdpProvider) => {
      if (app.protocol === IDP_PROVIDER_PROTOCOL.OAUTH) {
        oauthMutation.mutate(app);
      } else {
        samlMutation.mutate(app.id);
      }
    };

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

    const externalApps = appsData?.items || [];

    const displayLimit = showAll ? externalApps.length : MAX_LINKS;

    return (
      !!externalApps.length &&
      canViewExternalApps && (
        <Card sx={{ pb: 1 }}>
          <CardHeader
            title={
              <Typography
                variant="globalM"
                fontWeight="semiBold"
              >
                {t('external_tools')}
              </Typography>
            }
            sx={{ pb: 1 }}
          />
          <CardContent>
            <Stack
              sx={{
                flexDirection: 'row',
                flexWrap: 'wrap',
                alignItems: 'flex-start',
                justifyContent: 'flex-start',
                p: 1,
              }}
            >
              {externalApps?.slice(0, displayLimit).map(app => (
                <HuTooltip
                  key={app.id}
                  title={app.name}
                  direction="top"
                >
                  <Button
                    aria-label={app.name}
                    onClick={() => handleAppClick(app)}
                    sx={theme => ({
                      bgcolor: theme.palette.new.background.elements.grey,
                      minWidth: '64px',
                      minHeight: '64px',
                      maxWidth: '64px',
                      maxHeight: '64px',
                      objectFit: 'cover',
                      borderRadius: '50%',
                    })}
                  >
                    <WidgetIcon
                      icon={{ type: IconTypes.IMAGE, value: app.appIcon }}
                      width="40px"
                      height="40px"
                    />
                  </Button>
                </HuTooltip>
              ))}
            </Stack>
            {externalApps.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 ExternalToolsCard;
