import React, {useEffect, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconChevronLeft, IconChevronRight} from '@tabler/icons-react-native';
import {IconButton, Typography} from '@components';
import {useDebounceCallback} from '@hooks/useDebounceCallback';
import {getFormattedDate, isSameDay} from '@shared/utils';
import {useTheme} from '@shared/theme';

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

interface Props {
  initialDay: Date;
  onDayChange: (day: Date) => void;
}

export const HIT_SLOP = 16;

function DaySelector({initialDay, onDayChange}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const [day, setDay] = useState(initialDay);
  const isToday = isSameDay(day, new Date());
  const formattedDay = isToday
    ? t('general.today').toUpperCase()
    : getFormattedDate(day);

  const {debouncedCallback: onDateChangeDebounced} =
    useDebounceCallback(onDayChange);

  useEffect(() => {
    onDateChangeDebounced(day);
  }, [day, onDateChangeDebounced]);

  const onNextWeek = () => {
    setDay(onChangeDay('+'));
  };

  const onPreviousWeek = () => {
    setDay(onChangeDay('-'));
  };

  return (
    <View
      style={[
        styles.container,
        {
          backgroundColor: theme.background.layout.tertiary,
          borderColor: theme.border.neutral.default,
        },
      ]}>
      <IconButton
        hitSlop={HIT_SLOP}
        Icon={IconChevronLeft}
        onPress={onPreviousWeek}
        variant="flat"
      />
      <Typography align="center" style={styles.textContainer}>
        {formattedDay}
      </Typography>
      <IconButton
        hitSlop={HIT_SLOP}
        Icon={IconChevronRight}
        onPress={onNextWeek}
        variant="flat"
      />
    </View>
  );
}

export default DaySelector;
