import { useEffect } from 'react';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import useSnackbar from '@material-hu/components/design-system/Snackbar';

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

import { ListItem } from '../../components/ItemsList/ListItem';
import { useFormatStepTasks } from '../../hooks/useFormatStepTasks';
import { useGetJourneyTask } from '../../hooks/useGetJourneyTask';

type BlockedTaskWarningProps = {
  dependencyTaskId: number | null;
  clearDependencyTaskId: () => void;
};

export const BlockedTaskWarning = ({
  dependencyTaskId,
  clearDependencyTaskId,
}: BlockedTaskWarningProps) => {
  const { t } = useLokaliseTranslation('employee_lifecycle');
  const { enqueueSnackbar } = useSnackbar();

  // Get the dependent task
  // If task exists, task can be shown, show drawer
  // If task does not exist, task cant be shown, show snackbar
  const { task, isSuccess, isLoading } = useGetJourneyTask(dependencyTaskId);

  useEffect(() => {
    if (isLoading || !isSuccess) return;

    if (task) showDrawer({});
    else {
      enqueueSnackbar({
        title: t('dependency_task_dialog.title'),
        description: t('dependency_task_dialog.team_dependency'),
        variant: 'warning',
      });
      clearDependencyTaskId();
    }
  }, [isSuccess, isLoading, task]);

  const { completedTasks } = useFormatStepTasks({ tasks: task ? [task] : [] });

  const { showDrawer, drawer } = useDrawerV2(({ closeDrawer }) => ({
    title: t('dependency_task_dialog.title'),
    children: (
      <Stack sx={{ gap: 3 }}>
        <Typography variant="globalS">
          {t('dependency_task_dialog.personal_dependency')}
        </Typography>
        {task && (
          <ListItem
            item={completedTasks[0]}
            index={0}
          />
        )}
      </Stack>
    ),
    onClose: () => {
      closeDrawer();
      clearDependencyTaskId();
    },
    primaryButtonProps: {
      children: t('general:understood'),
      onClick: () => {
        closeDrawer();
        clearDependencyTaskId();
      },
      sx: { width: '100%' },
    },
  }));

  return <>{drawer}</>;
};
