import { useFormContext, useWatch } from 'react-hook-form';

import Dialog, {
  type DialogProps,
} from '@material-hu/components/design-system/Dialog';

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

import { type NewSessionFormValues } from '../../types';
import { isOldSession } from '../../utils';

type PublishSessionDialogProps = DialogProps & {
  onPublishSession: () => void;
  loading: boolean;
};

export const PublishSessionDialog = ({
  onPublishSession,
  onClose,
  loading,
}: PublishSessionDialogProps) => {
  const { t } = useLokaliseTranslation('learning');

  const { control } = useFormContext<NewSessionFormValues>();

  const [localDate, startTime, timeZone] = useWatch({
    control,
    name: [
      'basic_information.localDate',
      'basic_information.startTime',
      'basic_information.timeZone',
    ],
  });

  const isOld = isOldSession({ localDate, startTime, timeZone });

  return (
    <Dialog
      onClose={onClose}
      title={t('session.publish.modal.title')}
      textBody={
        isOld
          ? t('session.publish.modal.description_past_date')
          : t('session.publish.modal.description')
      }
      primaryButtonProps={{
        children: t('session.publish.title'),
        onClick: onPublishSession,
        loading,
        disabled: loading,
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: onClose,
      }}
    />
  );
};
