import { useEffect, useMemo, useState } from 'react';
import { FormProvider } from 'react-hook-form';
import { useNavigate } from 'react-router';

import { IconDownload, IconFilter } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton/IconButton';
import Stack from '@material-hu/mui/Stack';

import BadgeCountButton from '@material-hu/components/composed-components/BadgeCountButton';
import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import {
  calculateActiveCollaboratorFiltersCount,
  parseCoordinatorPanelFilters,
} from 'src/pages/dashboard/serviceManagement/utils';
import {
  type CoordinatorTaskFilters,
  type HydratedTask,
  ServiceManagementRole,
  type SmSortDirection,
  type SmSortField,
  type Task,
} from 'src/pages/dashboard/serviceManagement/types';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { hasAllPermissions, UserPermissions } from 'src/utils/permissions';

import { useModuleConfiguration } from '../../contexts/ModuleConfigurationContext';
import useAgentReassignment from '../../hooks/useAgentReassignment';
import useCoordinatorTasks from '../../hooks/useCoordinatorTasks';
import useTableSearchParams from '../../hooks/useTableSearchParams';
import { serviceManagementRoutes } from '../../routes';
import { coordinatorTaskFilters } from '../form/form';

import CollaboratorPanelFilterDrawer from './CollaboratorPanelFilterDrawer';
import DownloadTasksReportDrawer from './DownloadTasksReportDrawer';
import TasksTable from './TasksTable';

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

const CoordinatorTasks = ({
  helpDeskId,
  filters,
  onApplyFilters,
  onResetFilters,
  onCloseFilters,
}: Props) => {
  const { t } = useLokaliseTranslation(['service_management', 'general']);
  const navigate = useNavigate();

  const { permissions } = useAuth();

  const canDownloadTaskReport = useMemo(
    () =>
      hasAllPermissions(permissions, [
        UserPermissions.SERVICE_MANAGER_AGENT_REPORTS,
      ]),
    [permissions],
  );

  const [filterDrawerOpen, setFilterDrawerOpen] = useState(false);

  const [downloadReportDrawerOpen, setDownloadReportDrawerOpen] =
    useState(false);

  const {
    query: debouncedSearch,
    pagination,
    order,
    orderBy,
    HuTableSortingHeader,
    Pagination,
    Search,
    paginationForm,
  } = useTableSearchParams({
    defaultOrderBy: 'CREATED_AT',
    defaultOrder: 'DESC',
  });

  const params = useMemo(() => {
    return {
      helpDeskId,
      text: debouncedSearch || undefined,
      page: pagination.page,
      limit: pagination.limit,
      sortDirection: order as SmSortDirection,
      sortField: orderBy as SmSortField,
      ...parseCoordinatorPanelFilters(filters),
    };
  }, [helpDeskId, debouncedSearch, pagination, filters, order, orderBy]);

  const {
    data: tasks,
    isLoading,
    isPreviousData,
    isError,
    refetch,
  } = useCoordinatorTasks(params);

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

  const {
    handleOpenMultipleAssignmentMenu,
    handleOpenSingleAssignmentMenu,
    selectedTasks,
    setSelectedTasks,
    SingleAssignmentPopoverComponent,
    MultipleAssignmentPopoverComponent,
    multipleAssignmentConfirmationModal,
    singleAssignmentConfirmationModal,
  } = useAgentReassignment<Task>(params);

  useEffect(() => {
    logEvent(EventName.SERVICE_MGMT_COORDINATOR_LIST_VIEWED, {
      role: ServiceManagementRole.COORDINATOR,
    });
  }, []);

  const handleRowClick = (task: HydratedTask | Task) =>
    navigate(serviceManagementRoutes.agentSide.detail(task.id), {
      state: { navigatedFromServiceMgmt: true },
    });

  const handleCheckboxClick = (task: HydratedTask | Task) => {
    setSelectedTasks(prevSelected => {
      const isSelected = prevSelected.includes(task);
      if (isSelected) {
        return prevSelected.filter(prevTask => prevTask.id !== task.id);
      } else {
        return [...prevSelected, task];
      }
    });
  };

  const handleSelectAll = () => {
    if (selectedTasks.length > 0 && !allChecked) {
      setSelectedTasks([]);
      return;
    }

    const selectableTasks =
      tasks?.items.filter(task => !task.state.terminal) || [];
    setSelectedTasks(prevSelected =>
      prevSelected.length === selectableTasks.length && (tasks?.count || 0) > 0
        ? []
        : selectableTasks,
    );
  };

  const handleOpenSingleReassign = (taskToReasign: Task, index: number) => {
    const el = document.getElementById(`id-agent-row-${index}`);
    if (el) {
      handleOpenSingleAssignmentMenu(el, taskToReasign);
    }
  };

  const assignButtonDisabled = useMemo(() => {
    const serviceItemId = selectedTasks[0]?.catalogItem?.id;
    if (!serviceItemId) {
      return true;
    }
    return selectedTasks.some(task => task.catalogItem.id !== serviceItemId);
  }, [selectedTasks]);

  const allChecked = useMemo(() => {
    const selectableTasks =
      tasks?.items.filter(task => !task.state.terminal) || [];
    return !!(
      selectedTasks?.length > 0 &&
      tasks?.count &&
      tasks.count > 0 &&
      selectedTasks.length === selectableTasks.length
    );
  }, [selectedTasks, tasks]);

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

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

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

  const hasFilters = !!debouncedSearch || Object.keys(filters).length > 0;
  const hasSlasConfigured = Boolean(moduleConfiguration?.slaEnabled);

  if (isLoadingModuleConfiguration) {
    return (
      <Stack sx={{ pt: 3 }}>
        <HuSpinner />
      </Stack>
    );
  }

  return (
    <Stack gap={3}>
      <CollaboratorPanelFilterDrawer
        open={filterDrawerOpen}
        onClose={handleCloseFilterDrawer}
        onApply={handleApplyFilters}
        onReset={onResetFilters}
        helpDeskId={helpDeskId}
        filterConfig={coordinatorTaskFilters}
        showStatuses
        showRequesters
        showCollaboratorTypes
        showBack={downloadReportDrawerOpen}
      />
      <FormProvider {...paginationForm}>
        {multipleAssignmentConfirmationModal}
        {singleAssignmentConfirmationModal}
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 2,
            width: 1,
          }}
        >
          <Search
            inputProps={{
              placeholder: t('search_ticket'),
              disabled: isError,
            }}
          />
          <BadgeCountButton
            count={activeFiltersCount}
            buttonProps={{
              disabled: isLoading,
              variant: 'secondary',
              startIcon: <IconFilter />,
              onClick: () => setFilterDrawerOpen(true),
            }}
          >
            {activeFiltersCount > 0
              ? t('general:filtered')
              : t('general:filter')}
          </BadgeCountButton>
          {canDownloadTaskReport && (
            <>
              <HuTooltip description={t('download_report')}>
                <IconButton
                  aria-label={t('general:download')}
                  variant="secondary"
                  onClick={() => setDownloadReportDrawerOpen(true)}
                >
                  <IconDownload />
                </IconButton>
              </HuTooltip>
              <DownloadTasksReportDrawer
                open={downloadReportDrawerOpen}
                onClose={() => setDownloadReportDrawerOpen(false)}
                appliedFilters={filters}
                appliedFiltersCount={activeFiltersCount}
                helpDeskId={helpDeskId}
                filterType="coordinator"
                role={ServiceManagementRole.COORDINATOR}
              />
            </>
          )}
        </Stack>
        <TasksTable
          tasks={tasks}
          selectedTasks={selectedTasks}
          hasSearch={!!debouncedSearch}
          hasFilters={hasFilters}
          isLoadingTasks={isLoading}
          isError={isError}
          isPreviousData={isPreviousData}
          handleRowClick={handleRowClick}
          handleCheckboxClick={handleCheckboxClick}
          handleSelectAll={handleSelectAll}
          handleOpenSingleReassign={handleOpenSingleReassign}
          allChecked={allChecked}
          hasSlasConfigured={hasSlasConfigured}
          assignButtonDisabled={assignButtonDisabled}
          handleOpenMultipleAssignmentMenu={handleOpenMultipleAssignmentMenu}
          MultipleAssignmentPopoverComponent={
            MultipleAssignmentPopoverComponent
          }
          Pagination={Pagination}
          SortingHeader={HuTableSortingHeader}
          onRefetch={refetch}
          showAgentGroup={true}
        />
        {/* Popover is positioned outside the table element to prevent event propagations (not supported in onClose) */}
        {SingleAssignmentPopoverComponent}
      </FormProvider>
    </Stack>
  );
};

export default CoordinatorTasks;
