import { useMemo } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import { useLocation, useNavigate } from 'react-router-dom';

import HuTaskFocusHeader from '@material-hu/components/design-system/Header/TaskFocus';
import { type PillsProps } from '@material-hu/components/design-system/Pills';

import { sessionsRoutes } from 'src/pages/dashboard/Learning/Sessions/routes';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { SessionStatus } from '../../constants';
import { type NewSessionFormValues } from '../../types';

const SessionNewHeader = () => {
  const { control } = useFormContext<NewSessionFormValues>();
  const { t } = useLokaliseTranslation('learning');
  const navigate = useNavigate();
  const location = useLocation();

  const backRoute = location.state?.backRoute;

  const handleBack = () => {
    if (backRoute) navigate(backRoute);
    else navigate(sessionsRoutes.base());
  };

  const basicInformation = useWatch({
    control,
    name: 'basic_information',
  });

  const title = basicInformation?.title || t('session.create');
  const isDraft =
    basicInformation?.status === SessionStatus.draft && !!basicInformation?.id;

  const pill = useMemo(() => {
    let pillBody: PillsProps | undefined;

    if (isDraft) {
      pillBody = {
        type: 'neutral',
        label: t('session.status.draft'),
      };
    }

    if (basicInformation?.status === SessionStatus.published) {
      pillBody = {
        type: 'success',
        label: t('session.status.published_one'),
      };
    }

    return pillBody;
  }, [basicInformation, t]);

  return (
    <HuTaskFocusHeader
      key={title}
      title={title}
      onClose={handleBack}
      pillLabel={pill?.label}
      slotProps={{
        pill: { type: pill?.type },
        title: {
          withEllipsis: true,
          overflow: 'tooltip',
        },
      }}
    />
  );
};

export default SessionNewHeader;
