import React, {useEffect, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {InputDate, InputTime, Switch} from '@components';
import {SetState} from '@interfaces/generic';
import {PollConfiguration} from '@modules/post/interfaces';
import {addDays, roundToNearestMinutes} from '@shared/utils';

import {styles} from './styles';

const MINUTE_INTERVAL = 10;

interface Props {
  pollConfiguration: PollConfiguration;
  setPollConfiguration: SetState<PollConfiguration>;
  isError: boolean;
}

function PollEndTimeConfig({
  pollConfiguration,
  setPollConfiguration,
  isError,
}: Props) {
  const {t} = useTranslation();
  const now = new Date();
  const [endDate, setEndDate] = useState<Nullable<Date>>(
    pollConfiguration.endsAt,
  );
  const [endTime, setEndTime] = useState<Nullable<Date>>(
    pollConfiguration.endsAt,
  );

  useEffect(() => {
    setPollConfiguration((prev: PollConfiguration) => {
      let endsAt: Nullable<Date> = null;
      if (endDate && endTime) {
        endsAt = new Date(endDate);
        endsAt.setHours(endTime.getHours());
        endsAt.setMinutes(endTime.getMinutes());
      }
      return {
        ...prev,
        endsAt,
      };
    });
  }, [endDate, endTime, setPollConfiguration]);

  const onToggleHasEndTime = (hasEndTime: boolean) => {
    setEndDate(hasEndTime ? addDays(new Date(), 1) : null);
    setEndTime(
      hasEndTime
        ? roundToNearestMinutes(new Date(), {nearestTo: MINUTE_INTERVAL})
        : null,
    );
  };

  return (
    <View style={styles.endTimeContainer}>
      <Switch
        value={!!pollConfiguration.endsAt}
        onToggle={onToggleHasEndTime}
        title={t('post.set_end_time')}
        titleNumberOfLines={2}
        description={t('post.set_end_time_description')}
      />
      {!!(endDate && endTime) && (
        <>
          <InputDate
            label={t('post.date')}
            minDate={now}
            onChange={setEndDate}
            value={endDate}
          />
          <InputTime
            label={t('post.time')}
            value={endTime}
            minuteInterval={MINUTE_INTERVAL}
            onChange={setEndTime}
            isError={isError}
            helper={isError ? t('post.schedule_date_error') : undefined}
          />
        </>
      )}
    </View>
  );
}

export default PollEndTimeConfig;
