import { FC, useState } from 'react';

import { useInfiniteQuery, useQuery } from 'react-query';

import { IconArrowsRightLeft } from '@material-hu/icons/tabler';
import Grid from '@material-hu/mui/Grid';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Drawer from '@material-hu/components/design-system/Drawer';

import Tooltip from '@material-hu/components/design-system/Tooltip';
import useRequiredParams from 'src/hooks/useRequiredParams';
import {
  getMultiCompanyGroupCompanies,
  getMultiCompanyGroupCompaniesCount,
} from 'src/services/groups';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { getNextCursor } from 'src/utils/pagination';
import { InfiniteList } from 'src/components/list';

import { ButtonText } from '../../feed/components/ButtonText';
import { groupsKeys } from '../queries';

export const GroupCompaniesList: FC = () => {
  const { id: groupId } = useRequiredParams(['id']);
  const { t } = useTranslation(['group']);
  const [open, setOpen] = useState<boolean>(false);
  const { data: groupCompaniesCount } = useQuery(
    groupsKeys.multiCompany.count(groupId),
    () => getMultiCompanyGroupCompaniesCount(groupId),
  );

  const {
    data: groupCompanies,
    isSuccess,
    isLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useInfiniteQuery(
    groupsKeys.multiCompany.list(groupId),
    ({ pageParam }) => getMultiCompanyGroupCompanies(groupId, pageParam),
    {
      getNextPageParam: getNextCursor,
      enabled: open,
    },
  );

  const companies = groupCompanies?.pages.flatMap(page => page.data.items);

  return (
    <>
      <Tooltip
        description={t('group:multi_company_description')}
        direction="bottom"
      >
        <Stack
          direction="row"
          alignItems="center"
          gap={1}
          sx={{ mr: 0.5 }}
          onClick={() => setOpen(true)}
        >
          <IconArrowsRightLeft size={16} />
          <ButtonText>
            <Typography
              variant="globalS"
              fontWeight="semiBold"
              sx={theme => ({
                color: theme.palette.new.text.neutral.brand,
              })}
            >
              {t('group:multi_company')}
            </Typography>
          </ButtonText>
        </Stack>
      </Tooltip>
      <Drawer
        anchor="right"
        variant="temporary"
        open={open}
        onClose={() => setOpen(false)}
        title={t('group:multi_company_create_group')}
        primaryButtonProps={{
          children: t('general:accept'),
          fullWidth: true,
          onClick: () => setOpen(false),
        }}
      >
        <Typography
          fontWeight="fontWeightSemiBold"
          sx={{ mb: 2 }}
        >
          {t('group:group_companies')} ({groupCompaniesCount?.data?.count})
        </Typography>
        <Stack
          sx={theme => ({
            backgroundColor: theme.palette.new.background.layout.default,
            height: '100%',
            p: 2,
            borderRadius: theme.shape.borderRadiusL,
            overflowY: 'auto',
          })}
        >
          <InfiniteList
            isSuccess={isSuccess}
            isLoading={isLoading}
            isFetchingNextPage={isFetchingNextPage}
            hasNextPage={hasNextPage}
            fetchNextPage={fetchNextPage}
          >
            <Grid
              container
              spacing={2}
            >
              {companies?.map(company => (
                <Grid
                  key={company.instanceName}
                  item
                  xs={6}
                >
                  <Stack
                    alignItems="center"
                    sx={theme => ({
                      backgroundColor:
                        theme.palette.new.background.layout.tertiary,
                      p: 2,
                      borderRadius: theme.shape.borderRadiusL,
                      border: `1px solid ${theme.palette.new.border.neutral.default}`,
                    })}
                  >
                    <img
                      src={company.instanceLogo}
                      alt={company.instanceName}
                      style={{
                        objectFit: 'contain',
                        maxWidth: '100%',
                        maxHeight: '36px',
                        height: '100%',
                      }}
                    />
                    <Typography
                      variant="globalXXS"
                      sx={theme => ({
                        mt: 0.5,
                        color: theme.palette.new.text.neutral.lighter,
                      })}
                    >
                      {company.instanceName}
                    </Typography>
                  </Stack>
                </Grid>
              ))}
            </Grid>
          </InfiniteList>
        </Stack>
      </Drawer>
    </>
  );
};
