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

import { IconDiamonds } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import useTheme from '@material-hu/mui/styles/useTheme';
import Typography from '@material-hu/mui/Typography';

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

import { getActivities } from 'src/pages/dashboard/serviceManagement/services';
import {
  EventsType,
  type Task,
  TaskEventsViews,
  type UserTask,
} from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

import { getActivityIcon, isKnownActivityType } from '../../../constants';
import { serviceManagementKeys } from '../../../queries';

import ActivityDescription from './Activities/ActivityDescription';
import ApprovalsAvatar from './ApprovalsAvatar';
import ActivitiesSkeleton, {
  ActivitySkeleton,
} from './Skeletons/ActivitiesSkeleton';

export type ActivitiesProps = {
  taskData: Task;
  isAgentSide: boolean;
};

const Activities: FC<ActivitiesProps> = ({ taskData, isAgentSide }) => {
  const { t } = useLokaliseTranslation('service_management');
  const theme = useTheme();
  const viewsParam = isAgentSide
    ? [TaskEventsViews.ALL_DETAILED_EVENTS]
    : [TaskEventsViews.ALL_SIMPLIFIED_EVENTS];

  const {
    data: activitiesData,
    isLoading,
    isFetching,
    fetchNextPage,
    hasNextPage: hasMoreActivities,
    isFetchingNextPage,
  } = useInfiniteQuery(
    serviceManagementKeys.activities.list(taskData?.id!),
    ({ pageParam = null }) =>
      getActivities(taskData?.id!, pageParam, viewsParam, 10, true),
    {
      getNextPageParam: lastPage => lastPage.data.cursor || undefined,
      enabled: !!taskData?.id,
    },
  );

  const activities =
    activitiesData?.pages
      .flatMap(page => page.data.items)
      .filter(activity => isKnownActivityType(activity.type)) || [];

  const loading = isLoading || (isFetching && !isFetchingNextPage);

  return (
    <Stack
      sx={{
        backgroundColor: ({ palette }) =>
          palette.new.background.layout.tertiary,
        overflow: 'auto',
        scrollbarWidth: 'thin',
        scrollbarColor: 'rgba(0, 0, 0, 0.2) transparent',
      }}
    >
      {!isAgentSide && (
        <Stack
          sx={{
            px: 3,
            py: 2,
            top: 0,
            zIndex: 100,
            position: 'sticky',
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.tertiary,
          }}
        >
          <Typography
            variant="globalM"
            fontWeight="semiBold"
          >
            {t('activities')}
          </Typography>
        </Stack>
      )}
      {loading && <ActivitiesSkeleton />}
      {!loading && (
        <Stack
          id="activities-box"
          sx={{
            height: '100%',
            width: '100%',
            p: 3,
            pb: 0,
          }}
        >
          <InfiniteList
            isSuccess={!!activities}
            fetchNextPage={fetchNextPage}
            hasNextPage={hasMoreActivities}
            isFetchingNextPage={isFetchingNextPage}
            showNoResultsMessage={false}
            loadingSkeleton
            renderSkeleton={<ActivitySkeleton />}
          >
            <Stack
              sx={{
                gap: 3,
                pb: isFetchingNextPage ? 0 : 2,
                position: 'relative',
                mb: isFetchingNextPage ? 1 : 8,
              }}
            >
              {activities?.map((activity, index) => {
                const { Icon, color } = getActivityIcon(
                  activity.type,
                  activity.taskType,
                );

                const isApprovalActivity = [
                  EventsType.APPROVAL_TASK_APPROVED,
                  EventsType.APPROVAL_TASK_REJECTED,
                ].includes(activity.type);

                const isLastActivity = index === activities.length - 1;

                return (
                  <Stack
                    key={activity.id}
                    sx={{
                      flexDirection: 'row',
                      position: 'relative',
                      alignItems: 'center',
                      minHeight: '50px',
                      gap: 1,
                    }}
                  >
                    <Divider
                      orientation="vertical"
                      sx={{
                        height: isLastActivity ? '50px' : 'calc(100% + 70px)',
                        position: 'absolute',
                        zIndex: 0,
                        top: 30,
                        left: 20,
                        borderColor: theme =>
                          theme.palette.new.border.neutral.default,
                      }}
                    />
                    {!isApprovalActivity && (
                      <HuAvatar
                        variant="circular"
                        size="medium"
                        color={color}
                        Icon={Icon}
                        sx={{ zIndex: 20 }}
                      />
                    )}
                    {isApprovalActivity && (
                      <ApprovalsAvatar
                        task={{
                          ...activity.task,
                          assignee: activity.user as UserTask,
                        }}
                      />
                    )}
                    <ActivityDescription activity={activity} />
                    {isLastActivity && !hasMoreActivities && (
                      <Stack
                        sx={{
                          position: 'absolute',
                          zIndex: 10,
                          left: 11.5,
                          top: 78,
                        }}
                      >
                        <IconDiamonds
                          color={theme.palette.new.border.neutral.default}
                          size={18}
                        />
                      </Stack>
                    )}
                  </Stack>
                );
              })}
            </Stack>
          </InfiniteList>
        </Stack>
      )}
    </Stack>
  );
};

export default Activities;
