import { type FC, useMemo, useState } from 'react';

import { type AxiosResponse } from 'axios';
import { IconFilter } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import BadgeCountButton from '@material-hu/components/composed-components/BadgeCountButton';
import HuTitle from '@material-hu/components/design-system/Title';

import {
  type CollaboratorPanelFilters,
  type HelpDeskAssociatedMember,
} from 'src/pages/dashboard/serviceManagement/types';
import { calculateActiveCollaboratorFiltersCount } from 'src/pages/dashboard/serviceManagement/utils';
import { type Pagination } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useModuleConfiguration } from '../../contexts/ModuleConfigurationContext';
import useCoordinatorDashboard from '../../hooks/useCoordinatorDashboard';
import { coordinatorDashboardFilters } from '../form/form';

import AssociatedMembers from './AssociatedMembers/AssociatedMembers';
import CollaboratorPanelFilterDrawer from './CollaboratorPanelFilterDrawer';
import ServiceMetrics from './ServiceMetrics/ServiceMetrics';

type Props = {
  helpDeskId: string;
  helpDeskName?: string;
  filters: CollaboratorPanelFilters;
  onApplyFilters: () => void;
  onResetFilters: () => void;
  onCloseFilters: () => void;
};

const HelpDeskGeneralView: FC<Props> = ({
  helpDeskId,
  helpDeskName,
  filters,
  onApplyFilters,
  onResetFilters,
  onCloseFilters,
}) => {
  const { t } = useLokaliseTranslation(['service_management', 'general']);

  const [isFilterDrawerOpen, setIsFilterDrawerOpen] = useState(false);

  const {
    moduleQuery: { data: moduleConfiguration },
  } = useModuleConfiguration();

  const {
    serviceMetrics,
    isLoadingServiceMetrics,
    isErrorServiceMetrics,
    refetchServiceMetrics,
    serviceMetricsChartData,
    isRefetchingServiceMetrics,
    associatedMembersInfiniteQuery,
  } = useCoordinatorDashboard({
    helpDeskId,
    filters,
  });

  const handleOpenFilterDrawer = () => setIsFilterDrawerOpen(true);

  const handleCloseFilterDrawer = () => {
    onCloseFilters();
    setIsFilterDrawerOpen(false);
  };

  const handleApplyFilters = () => {
    onApplyFilters();
    setIsFilterDrawerOpen(false);
  };

  const activeFiltersCount = useMemo(() => {
    return calculateActiveCollaboratorFiltersCount(filters);
  }, [filters]);

  const hasCsat = moduleConfiguration?.csatEnabled ?? false;

  const associatedMembers =
    associatedMembersInfiniteQuery.data?.pages.flatMap(
      (page: AxiosResponse<Pagination<HelpDeskAssociatedMember[]>>) =>
        page.data.items,
    ) || [];

  return (
    <Stack sx={{ gap: 3 }}>
      <CollaboratorPanelFilterDrawer
        open={isFilterDrawerOpen}
        onClose={handleCloseFilterDrawer}
        onApply={handleApplyFilters}
        onReset={onResetFilters}
        helpDeskId={helpDeskId}
        filterConfig={coordinatorDashboardFilters}
      />
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          gap: 4,
        }}
      >
        <HuTitle
          title={t('help_desk_general_view_title')}
          variant="M"
        />
        <BadgeCountButton
          count={activeFiltersCount}
          buttonProps={{
            variant: 'secondary',
            size: 'small',
            startIcon: <IconFilter />,
            onClick: handleOpenFilterDrawer,
          }}
        >
          {activeFiltersCount > 0 ? t('general:filtered') : t('general:filter')}
        </BadgeCountButton>
      </Stack>
      <ServiceMetrics
        serviceMetrics={serviceMetrics}
        helpDeskName={helpDeskName}
        hasCsat={hasCsat}
        isLoading={isLoadingServiceMetrics || isRefetchingServiceMetrics}
        isError={isErrorServiceMetrics}
        onRetry={refetchServiceMetrics}
        serviceMetricsChartData={serviceMetricsChartData}
      />
      <AssociatedMembers
        isLoading={
          associatedMembersInfiniteQuery.isLoading ||
          ((associatedMembersInfiniteQuery.isRefetching ||
            associatedMembersInfiniteQuery.isFetching) &&
            !associatedMembersInfiniteQuery.isFetchingNextPage)
        }
        isError={!!associatedMembersInfiniteQuery.isError}
        onRetry={associatedMembersInfiniteQuery.refetch}
        associatedMembers={associatedMembers}
        hasCsat={hasCsat}
        hasFilters={activeFiltersCount > 0}
        isSuccess={associatedMembersInfiniteQuery.isSuccess}
        isFetchingNextPage={
          associatedMembersInfiniteQuery.isFetchingNextPage || false
        }
        hasNextPage={!!associatedMembersInfiniteQuery.hasNextPage}
        fetchNextPage={associatedMembersInfiniteQuery.fetchNextPage}
      />
    </Stack>
  );
};

export default HelpDeskGeneralView;
