import React, {
  useMemo,
  useRef,
  useState,
  useLayoutEffect,
  useEffect,
} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useNetInfo} from '@react-native-community/netinfo';
import {
  BottomModalFooter,
  INPUT_STYLES,
  InputClassic,
  ListRow,
  Typography,
  DismissKeyboard,
  Alert,
} from '@components';
import {ApiErrors, HumandAPIError} from '@config/api';
import {Navigation} from '@interfaces/navigation';
import Clock from '@modules/timeTracking/components/Clock';
import {openTimeTracker} from '@modules/timeTracking/redux';
import {useTimeTracker, useTimeoutHandler} from '@modules/timeTracking/hooks';
import {useAppSelector} from '@redux/utils';
import {showSnackbar} from '@redux/dispatchers';
import {useUser} from '@redux/selectors';
import {MAX_INPUT_LENGTH, Screens} from '@shared/constants';
import {getCompleteName} from '@shared/utils';
import {useTheme} from '@shared/theme';

import {styles} from './styles';
import {getDisplayDate} from './utils';

function TrackerComment({
  navigation,
  route: {
    params: {selectedLocation, faceRejected},
  },
}: Navigation<Screens.TRACKER_COMMENT>) {
  const {theme} = useTheme();
  const {t} = useTranslation();
  const {isInternetReachable} = useNetInfo();
  const shouldOpenModal = useRef(false);
  const user = useUser();
  const position = useAppSelector(({timeTracking}) => timeTracking.position);
  const [message, setMessage] = useState('');
  const {
    addNewRegister,
    addNewRegisterLoading,
    trackerInfo: {
      active,
      currentRegisterStartTime,
      daySummary,
      hasWorkSchedule,
      scheduledTimeSeconds,
      seconds,
    },
  } = useTimeTracker();
  const isFreeDay = hasWorkSchedule && !daySummary?.isWorkday;
  const isStart = !active;

  const excessTime = useMemo(
    () => Math.max(seconds - scheduledTimeSeconds, 0),
    [scheduledTimeSeconds, seconds],
  );

  const displayDate = useMemo(() => getDisplayDate(), []);

  useTimeoutHandler();

  useLayoutEffect(() => {
    navigation.setOptions({
      title: t(isStart ? 'time_tracker.init_clock' : 'time_tracker.stop_clock'),
    });
  }, [isStart, navigation, t]);

  useEffect(() => {
    const beforeRemove = navigation.addListener('beforeRemove', () => {
      if (shouldOpenModal.current) {
        openTimeTracker();
      }
    });
    return () => {
      beforeRemove();
    };
  }, [navigation]);

  const onConfirmAction = () => {
    if (!addNewRegisterLoading) {
      requestAnimationFrame(() => {
        addNewRegister({
          onInternalSuccess: () => {
            if (isStart) {
              shouldOpenModal.current = true;
            } else {
              showSnackbar({title: t('time_tracker.stopped_clock')});
            }
            navigation.popToTop();
          },
          onInternalError: (error: HumandAPIError) => {
            if (error?.code === ApiErrors.TIME_TRACKING_ENTRY_DUPLICATE) {
              shouldOpenModal.current = false;
              navigation.popToTop();
              showSnackbar({
                title: t('time_tracker.register_error_title'),
                description: t('time_tracker.register_error_description'),
                variant: 'error',
              });
            }
          },
          siteId: selectedLocation?.id,
          comment: message,
          location: position,
          facialRecognitionSkipped: faceRejected,
        });
      });
    }
  };

  return (
    <DismissKeyboard
      style={[
        styles.container,
        {backgroundColor: theme.background.layout.tertiary},
      ]}>
      <View style={styles.topContainer}>
        <ListRow>
          <ListRow.Avatar
            name={getCompleteName(user)}
            url={user.profilePicture}
          />
          <ListRow.Title title={getCompleteName(user)} />
        </ListRow>
        <View
          style={[
            styles.clockAndSite,
            {backgroundColor: theme.background.layout.default},
          ]}>
          <Typography weight="semiBold">{t('time_tracker.marking')}</Typography>
          <View>
            <Clock
              showSeconds
              excessTime={hasWorkSchedule || isFreeDay ? excessTime : null}
              accumulatedSeconds={seconds}
              currentRegisterStartTime={currentRegisterStartTime}
              isActive={active}
              variant="s"
            />
            <View style={styles.site}>
              <Typography
                variant="xs"
                color={theme.text.neutral.lighter}
                numberOfLines={1}>
                {selectedLocation
                  ? selectedLocation.location.address
                    ? `${selectedLocation.name} - ${selectedLocation.location.address}`
                    : selectedLocation.name
                  : t('time_tracker.current_location')}
              </Typography>
              <Typography
                color={theme.text.neutral.lighter}
                variant="xs"
                weight="semiBold">
                {displayDate}
              </Typography>
            </View>
          </View>
          {!isInternetReachable && (
            <Alert
              title={t('time_tracker.marking_offline')}
              description={t('time_tracker.marking_offline_desc')}
              variant="warning"
            />
          )}
        </View>
        <InputClassic
          multiline
          showCounter
          label={t('time_tracker.notes')}
          maxLength={MAX_INPUT_LENGTH}
          onChangeText={setMessage}
          placeholder={t('time_tracker.write_to_supervisor')}
          returnKeyType="done"
          style={INPUT_STYLES.longInputSpacing}
          value={message}
        />
      </View>
      <BottomModalFooter
        footer={{
          primaryButton: {
            isLoading: addNewRegisterLoading,
            onPress: onConfirmAction,
            text: t(
              isStart ? 'time_tracker.init_clock' : 'time_tracker.stop_clock',
            ),
          },
          secondaryButton: {
            disabled: addNewRegisterLoading,
            onPress: navigation.popToTop,
            text: t('time_tracker.not_now'),
          },
        }}
        style={styles.bottomContainer}
      />
    </DismissKeyboard>
  );
}

export default TrackerComment;
