import type { PageSectionComponent } from '../types';
import type { CountdownSectionProps } from './types';

import { ItemTypes } from '~/lib/types';
import Box from '~/src/components/Box';
import InputLabel from '~/src/components/InputLabel';
import Notification, { NotificationType } from '~/src/components/Notification';
import TextInput from '~/src/components/TextInput';
import { useI18n } from '~/src/lib/i18n';
import { useEditActions } from '../../ItemPageEdit/useEditActions';
import { EditWrapper } from '../lib/EditWrapper';
import { CountdownSectionView } from './CountdownSectionView';
import { getReleaseTimestamp } from './utils';

const CountdownSectionEdit: PageSectionComponent<CountdownSectionProps> = ({
  sectionPath,
  title,
  layoutData: { item },
}) => {
  if (item.type !== ItemTypes.PRERELEASE)
    throw new Error(`Countdown is not supported for item type: ${item.type}`);

  const { releaseDate, releaseTimezone } = item;

  const { t } = useI18n('itemEdit');
  const { updateLayoutSection } = useEditActions();

  const releaseTimestamp = getReleaseTimestamp(releaseDate, releaseTimezone);
  const remainingTime = releaseTimestamp - Date.now();

  return (
    <Box testId="countdownSectionEdit">
      <EditWrapper
        sectionPath={sectionPath}
        padding="1.6rem 1rem 2rem"
        renderSettingsContent={() => (
          <InputLabel value={t('labels.componentTitle')}>
            <TextInput
              testId="countdownSectionTitleInput"
              defaultValue={title}
              placeholder={t('countdownSection.edit.title')}
              onChange={({ value }) => {
                updateLayoutSection({
                  sectionPath,
                  changedProps: { title: value },
                });
              }}
            />
          </InputLabel>
        )}
      >
        <CountdownSectionView
          title={title}
          releaseTimestamp={releaseTimestamp}
        />
        {remainingTime < 0 && (
          <Box padding="1.2rem 1.2rem 0">
            <Notification
              type={NotificationType.WARNING}
              textSize="1.3rem"
              content={t('countdownSection.edit.pastReleaseDateWarning')}
            />
          </Box>
        )}
      </EditWrapper>
    </Box>
  );
};

export default CountdownSectionEdit;
