import React from 'react';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router';
import { Badge } from 'reactstrap';
 
import {
TIME_RANGE_END_PARAM,
TIME_RANGE_MODES,
TIME_RANGE_PARAM_BY_MODE,
TIME_RANGE_START_PARAM,
} from '../utils/timeRangeUtils';
 
/**
* Displays the selected time range and allows the user to remove it.
* The active range mode is resolved from the URL because the badge belongs to Alerts.
*/
export function CustomRangeBadge({ isLoading }) {
const { t } = useTranslation();
const [searchParams, setSearchParams] = useSearchParams();
 
const lastActivityKey = TIME_RANGE_PARAM_BY_MODE[TIME_RANGE_MODES.LAST_ACTIVITY];
const mode = searchParams.has(`${lastActivityKey}.${TIME_RANGE_START_PARAM}`)
|| searchParams.has(`${lastActivityKey}.${TIME_RANGE_END_PARAM}`)
? TIME_RANGE_MODES.LAST_ACTIVITY
: TIME_RANGE_MODES.CREATED_AT;
const rangeKey = TIME_RANGE_PARAM_BY_MODE[mode];
 
const startTimestamp = searchParams.get(`${rangeKey}.${TIME_RANGE_START_PARAM}`);
const endTimestamp = searchParams.get(`${rangeKey}.${TIME_RANGE_END_PARAM}`);
 
const dateTypeLabel = mode === TIME_RANGE_MODES.LAST_ACTIVITY
? t('AlertsListScreen|Last activity')
: t('AlertsListScreen|Created at');
 
const formatDate = (timestamp) => {
if (timestamp == null || !Number.isFinite(Number(timestamp))) {
return null;
}
 
const date = new Date(Number(timestamp));
 
return Number.isNaN(date.getTime()) ? null : date.toLocaleString();
};
 
const start = formatDate(startTimestamp);
const end = formatDate(endTimestamp);
 
if (!start && !end) {
return null;
}
 
const dateRange = start && end
? `${start} – ${end}`
: start || end;
 
const handleRemove = () => {
setSearchParams((prevSearchParams) => {
const updatedParams = new URLSearchParams(prevSearchParams);
 
updatedParams.delete(`${rangeKey}.${TIME_RANGE_START_PARAM}`);
updatedParams.delete(`${rangeKey}.${TIME_RANGE_END_PARAM}`);
updatedParams.set('p', '1');
 
return updatedParams;
});
};
 
return (
<Badge pill color='primary'>
{`${dateTypeLabel}: ${dateRange}`}
<i
className={`bi bi-x ps-1${isLoading ? '' : ' datatable-cardpill-icon'}`}
title={t('General|Remove')}
onClick={isLoading ? undefined : handleRemove}
/>
</Badge>
);
}