import { type FC } from 'react';
import { type InfiniteQueryObserverBaseResult } from 'react-query';

import {
  IconAlertSquareRounded,
  IconAlertTriangle,
  IconInbox,
  IconMoodSmile,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuStateCard from '@material-hu/components/composed-components/StateCard';
import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuTitle from '@material-hu/components/design-system/Title';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { type HelpDeskAssociatedMember } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName, getInitials } from 'src/utils/userUtils';

import { InfiniteList } from 'src/components/list';

import { parseAverageRating } from '../../utils';

import AssociatedMembersSkeleton from './AssociatedMembersSkeleton';

type Props = {
  associatedMembers: HelpDeskAssociatedMember[] | undefined;
  hasCsat: boolean;
  isLoading: boolean;
  isError: boolean;
  onRetry: () => void;
  hasFilters: boolean;
  isSuccess: boolean;
} & Pick<
  InfiniteQueryObserverBaseResult,
  'isFetchingNextPage' | 'hasNextPage' | 'fetchNextPage'
>;

const AssociatedMembers: FC<Props> = ({
  associatedMembers,
  hasCsat,
  isLoading,
  isError,
  onRetry,
  hasFilters,
  isSuccess,
  isFetchingNextPage,
  hasNextPage,
  fetchNextPage,
}) => {
  const { t } = useLokaliseTranslation('service_management');

  if (isLoading) {
    return (
      <HuCardContainer fullWidth>
        <Stack sx={{ gap: 2 }}>
          <HuTitle
            variant="M"
            title={t('associated_members')}
            description={t('associated_members_description')}
          />
          <AssociatedMembersSkeleton />
        </Stack>
      </HuCardContainer>
    );
  }

  if (isError) {
    return (
      <HuStateCard
        slotProps={{
          title: {
            variant: 'S',
            title: t('error_cant_show_associated_members'),
            description: t('try_again_later'),
          },
          avatar: {
            Icon: IconAlertTriangle,
            color: 'error',
          },
          button: {
            children: t('try_again'),
            variant: 'secondary',
            onClick: onRetry,
          },
        }}
        sx={{
          py: 6,
        }}
      />
    );
  }

  const hasMembers = !!associatedMembers && associatedMembers.length > 0;
  const showNoResultsForSearch = !hasMembers && hasFilters;
  const showEmptyState = !hasMembers && !hasFilters;

  if (showEmptyState) {
    return (
      <HuStateCard
        slotProps={{
          title: {
            variant: 'S',
            title: t('no_associated_members_yet'),
            description: t('no_associated_members_yet_description'),
          },
          avatar: {
            Icon: IconAlertSquareRounded,
            color: 'primary',
          },
        }}
        sx={{
          p: 3,
        }}
      />
    );
  }

  if (showNoResultsForSearch) {
    return (
      <HuStateCard
        slotProps={{
          title: {
            variant: 'S',
            title: t('no_results_for_selection'),
            description: t('try_with_other_filters'),
          },
          avatar: {
            Icon: IconAlertSquareRounded,
            color: 'primary',
          },
        }}
        sx={{
          p: 3,
        }}
      />
    );
  }

  return (
    <HuCardContainer fullWidth>
      <Stack sx={{ gap: 2 }}>
        <HuTitle
          variant="M"
          title={t('associated_members')}
          description={t('associated_members_description')}
        />
        <InfiniteList
          isSuccess={isSuccess}
          isLoading={false}
          isEmpty={false}
          fetchNextPage={fetchNextPage}
          hasNextPage={hasNextPage}
          isFetchingNextPage={isFetchingNextPage}
          renderSkeleton={
            <Stack sx={{ mt: 2 }}>
              <AssociatedMembersSkeleton />
            </Stack>
          }
        >
          <Stack
            sx={{
              display: 'grid',
              gap: 2,
              width: 1,
              gridTemplateColumns: {
                xs: '1fr',
                sm: 'repeat(2, 1fr)',
                md: 'repeat(2, 1fr)',
                lg: 'repeat(3, 1fr)',
                xl: 'repeat(4, 1fr)',
              },
            }}
          >
            {associatedMembers?.map(member => {
              const fullName = getFullName(member.user);
              return (
                <Stack
                  key={member.user.id}
                  sx={{
                    gap: 1,
                    backgroundColor: ({ palette }) =>
                      palette.new.background.layout.default,
                    borderRadius: 2,
                    p: 2,
                    minWidth: 0,
                  }}
                >
                  <Stack
                    sx={{ flexDirection: 'row', gap: 1, alignItems: 'center' }}
                  >
                    <HuAvatar
                      src={member.user.profilePicture || undefined}
                      text={getInitials(fullName)}
                      alt={fullName}
                    />
                    <HuTitle
                      title={fullName}
                      withEllipsis
                      overflow="tooltip"
                      description={t('associated_members_count', {
                        count: member.agentGroupCount,
                      })}
                      variant="S"
                    />
                  </Stack>
                  <HuCardContainer
                    padding={16}
                    fullWidth
                    sx={{
                      backgroundColor: ({ palette }) =>
                        palette.new.background.layout.tertiary,
                    }}
                  >
                    <Stack
                      sx={{
                        gap: 1,
                        alignItems: 'center',
                        flexDirection: 'row',
                        width: 1,
                      }}
                    >
                      <Stack
                        sx={{
                          flex: 1,
                          flexDirection: 'row',
                          gap: 1,
                          alignItems: 'center',
                        }}
                      >
                        <HuTooltip description={t('agent_open_tasks_tooltip')}>
                          <Stack
                            sx={{
                              flexDirection: 'row',
                              alignItems: 'center',
                              gap: 1,
                            }}
                          >
                            <HuAvatar
                              Icon={IconInbox}
                              size="small"
                              alt=""
                              variant="rounded"
                            />
                            <Typography
                              variant="globalM"
                              fontWeight="fontWeightSemiBold"
                            >
                              {member.openTaskCount}
                            </Typography>
                          </Stack>
                        </HuTooltip>
                      </Stack>
                      {hasCsat && (
                        <>
                          <Divider
                            orientation="vertical"
                            flexItem
                          />
                          <Stack
                            sx={{
                              flex: 1,
                              flexDirection: 'row',
                              gap: 1,
                              alignItems: 'center',
                            }}
                          >
                            <HuTooltip
                              description={t('agent_csat_rating_tooltip')}
                            >
                              <Stack
                                sx={{
                                  flexDirection: 'row',
                                  alignItems: 'center',
                                  gap: 1,
                                }}
                              >
                                <HuAvatar
                                  Icon={IconMoodSmile}
                                  size="small"
                                  alt=""
                                  variant="rounded"
                                />
                                <Typography
                                  variant="globalM"
                                  fontWeight="fontWeightSemiBold"
                                >
                                  {parseAverageRating(member.averageRating)}
                                </Typography>
                              </Stack>
                            </HuTooltip>
                          </Stack>
                        </>
                      )}
                    </Stack>
                  </HuCardContainer>
                </Stack>
              );
            })}
          </Stack>
        </InfiniteList>
      </Stack>
    </HuCardContainer>
  );
};

export default AssociatedMembers;
