import { useState } from 'react';

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

import { useLokaliseTranslation } from 'src/utils/i18n';

import { useFilterParams } from '../../../hooks/useFilterParams';
import { useGetJourneyStepTasks } from '../../../hooks/useGetJourneyStepTasks';
import {
  JourneyTaskStatus,
  StepTasksTabs,
  StepTasksTabsType,
} from '../../../types';
import TasksFilters from '../TasksFilters';

import { CompletedTasksTab } from './CompletedTasksTab';
import { PendingTasksTab } from './PendingTasksTab';

const tabComponents = {
  [StepTasksTabs.PENDING_TASKS]: PendingTasksTab,
  [StepTasksTabs.COMPLETED_TASKS]: CompletedTasksTab,
};

type TaskTabsProps = {
  isUserTasksModule?: boolean;
};

export const TaskTabs = ({ isUserTasksModule = false }: TaskTabsProps) => {
  const { t } = useLokaliseTranslation('employee_lifecycle');
  const { clearFilters } = useFilterParams();
  const [tab, setTab] = useState<StepTasksTabsType>('PENDING_TASKS');

  const hidePillFilters = tab === 'COMPLETED_TASKS';

  const handleChangeTab = (value: string) => {
    setTab(value as StepTasksTabsType);
    clearFilters();
  };

  const tabs = Object.values(StepTasksTabs).map(tabItem => ({
    label: t(`tabs.${tabItem.toLowerCase()}`),
    value: tabItem,
  }));

  const progressStatus =
    tab === 'PENDING_TASKS'
      ? // We get PENDING & IN_PROGRESS tasks for the step
        [JourneyTaskStatus.NOT_STARTED, JourneyTaskStatus.IN_PROGRESS]
      : // We get DONE tasks for the step
        [JourneyTaskStatus.DONE];

  const { paginatedTasks, uniqueCollaborators, pagination, isLoading } =
    useGetJourneyStepTasks({
      progressStatus,
      isUserTasksModule,
    });

  const CurrentTab = tabComponents[tab];

  return (
    <>
      <HuTabs
        tabs={tabs}
        value={tab}
        onTabChange={handleChangeTab}
        defaultValue={tab}
      />
      <TasksFilters
        isUserTasksModule={isUserTasksModule}
        hidePillFilters={hidePillFilters}
        collaborators={uniqueCollaborators}
      />
      <CurrentTab
        tasks={paginatedTasks}
        pagination={pagination}
        isLoading={isLoading}
        isUserTasksModule={isUserTasksModule}
      />
    </>
  );
};
