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

import { getNow } from '@material-hu/utils/time';

import { SessionStatus } from '../constants';
import { sessionsRoutes } from '../routes';
import { type NewSessionFormValues, type SessionStatusType } from '../types';

export const useSessionStatus = () => {
  const { control } = useFormContext<NewSessionFormValues>();
  const params = useParams();
  const sessionId = params.id ? parseInt(params.id) : undefined;
  const isEditingSession =
    sessionId && !!useMatch(sessionsRoutes.edit(sessionId));

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

  const isSessionFinished = status === SessionStatus.finished;

  const isSessionEndDatePassed = useMemo(() => {
    if (!endTime) return false;
    return new Date() > endTime;
  }, [endTime]);

  const isSessionInProgress = useMemo(() => {
    if (status === SessionStatus.draft) return false;
    if (!startTime || !endTime) return false;

    const now = getNow(timeZone);
    return now >= startTime && now <= endTime;
  }, [startTime, endTime, timeZone]);

  const blockSessionEdition = Boolean(
    isEditingSession && (isSessionInProgress || isSessionFinished),
  );

  const isSessionDraft = status === SessionStatus.draft;
  const blockNotificationsEdition = Boolean(
    isSessionDraft && isSessionEndDatePassed,
  );

  const sessionStatus: SessionStatusType = isSessionFinished
    ? SessionStatus.finished
    : SessionStatus.inProgress;

  return {
    isEditingSession,
    isSessionInProgress,
    isSessionFinished,
    isSessionEndDatePassed,
    blockSessionEdition,
    blockNotificationsEdition,
    sessionStatus,
  };
};
