import React, {useCallback, useEffect, useState} from 'react';
import {useTranslation} from 'react-i18next';
import {useNavigation} from '@react-navigation/native';
import {Dialog, Typography} from '@components';
import {useAppStateChange} from '@hooks/useAppStateChange';
import {
  useGeolocation,
  useTimeoutHandler,
  useTimeTracker,
} from '@modules/timeTracking/hooks';
import {
  DescriptorKey,
  PositionError,
  TimeTrackerConfig,
} from '@modules/timeTracking/interfaces';
import {closeTimeTracker} from '@modules/timeTracking/redux';
import {usePermission} from '@redux/selectors';
import {useAppSelector} from '@redux/utils';
import {AMPLITUDE_EVENTS, Screens} from '@shared/constants';
import {logAmplitudeEvent} from '@shared/utils';
import {useCommunityFeature} from '@stores/communityFeatures';

import CheckerClock from './components/CheckerClock';
import CheckerClockLoaderSk from './components/CheckerClockLoaderSk';
import CheckerList from './components/CheckerList';

function TimeTracker({
  initialDescriptor = 'checkerWatch',
  isStarting = false,
}: TimeTrackerConfig) {
  const {t} = useTranslation();
  const navigation = useNavigation();
  const canViewShifts = usePermission('VIEW_SHIFTS');
  const locationError = useAppSelector(
    ({timeTracking}) => timeTracking.locationError,
  );
  const hideCheckHistory = useCommunityFeature(
    'TIME_TRACKING_HIDE_CHECK_HISTORY',
  );
  const [descriptor, setDescriptor] =
    useState<DescriptorKey>(initialDescriptor);
  const {getAllRegistersAndExtraData, isLoadingAllData, trackerInfo} =
    useTimeTracker();
  const {onGetCurrentLocation} = useGeolocation();
  const isTimeToStart = descriptor === 'timeToStart';
  const isNotification = isTimeToStart || descriptor === 'timeToFinish';
  const hasFakeGPS = locationError === PositionError.MOCK_ERROR;

  useAppStateChange({onChangeToBackground: closeTimeTracker});

  useTimeoutHandler();

  useEffect(() => {
    if (isStarting && descriptor === 'checkerWatch') {
      logAmplitudeEvent(AMPLITUDE_EVENTS.TIME_TRACKING_CLOCK_OPENED, {
        hasFakeGPS,
      });
      getAllRegistersAndExtraData();
      // setTimeout to avoid blocking the UI
      setTimeout(() => {
        onGetCurrentLocation({startTime: new Date()});
      }, 1500);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [descriptor]);

  const onCheckHistory = useCallback(() => {
    closeTimeTracker();
    navigation.navigate(Screens.CHECK_HISTORY);
  }, [navigation]);

  const onGoToCheck = useCallback(() => {
    requestAnimationFrame(() => {
      setDescriptor('checkerWatch');
    });
  }, []);

  const onCheckCalendar = useCallback(() => {
    closeTimeTracker();
    navigation.navigate(Screens.SHIFTS_CALENDAR, {isFromTracker: true});
  }, [navigation]);

  return (
    <Dialog
      isVisible
      footer={
        isNotification
          ? {
              primaryButton: {
                text: t('time_tracker.open_clock'),
                onPress: onGoToCheck,
              },
              secondaryButton: {
                text: t('time_tracker.not_now'),
                onPress: closeTimeTracker,
              },
            }
          : hideCheckHistory && !canViewShifts
          ? undefined
          : {
              primaryButton: {
                disabled: isLoadingAllData,
                onPress: canViewShifts ? onCheckCalendar : onCheckHistory,
                text: t(
                  canViewShifts
                    ? 'work_schedules.shifts'
                    : 'time_tracker.check_history',
                ),
                variant: 'secondary',
              },
              secondaryButton:
                !hideCheckHistory && canViewShifts
                  ? {
                      disabled: isLoadingAllData,
                      onPress: onCheckHistory,
                      text: t('time_tracker.check_history'),
                    }
                  : undefined,
            }
      }
      onClose={closeTimeTracker}
      title={t(
        `time_tracker.${
          isNotification
            ? isTimeToStart
              ? 'time_to_start'
              : 'time_to_finish'
            : 'checker_clock'
        }`,
      )}
      withCloseButton={false}>
      {isNotification ? (
        <Typography>
          {t(
            `time_tracker.${
              isTimeToStart
                ? 'time_to_start_description'
                : 'time_to_finish_description'
            }`,
          )}
        </Typography>
      ) : isLoadingAllData ? (
        <CheckerClockLoaderSk />
      ) : (
        <>
          <CheckerClock trackerInfo={trackerInfo} />
          {!hideCheckHistory && <CheckerList trackerInfo={trackerInfo} />}
        </>
      )}
    </Dialog>
  );
}

export default TimeTracker;
