import { css } from '@emotion/css';

import { type GrafanaTheme2 } from '@grafana/data';
import { Trans, t } from '@grafana/i18n';
import { config } from '@grafana/runtime';
import { Box, Tab, TabContent, TabsBar, Text, useStyles2 } from '@grafana/ui';
import { useQueryParams } from 'app/core/hooks/useQueryParams';

import { NotificationsScene } from '../../../notifications/NotificationsScene';
import { withPageErrorBoundary } from '../../../withPageErrorBoundary';
import { AlertingPageWrapper } from '../../AlertingPageWrapper';

import { CentralAlertHistoryScene } from './CentralAlertHistoryScene';

enum ActiveTab {
  AlertEvents = 'alert_events',
  Notifications = 'notifications',
}

function HistoryPage() {
  const styles = useStyles2(getStyles);
  const [queryParams, setQueryParams] = useQueryParams();
  const notificationsEnabled = config.featureToggles.alertingNotificationHistoryGlobal;

  const activeTab =
    notificationsEnabled && queryParams.tab === ActiveTab.Notifications
      ? ActiveTab.Notifications
      : ActiveTab.AlertEvents;

  return (
    <AlertingPageWrapper navId="alerts-history" isLoading={false}>
      {notificationsEnabled && (
        <TabsBar>
          <Tab
            label={t('alerting.central-alert-history.tab.alert-events', 'Alert events')}
            active={activeTab === ActiveTab.AlertEvents}
            onChangeTab={() => setQueryParams({ tab: ActiveTab.AlertEvents })}
          />
          <Tab
            label={t('alerting.central-alert-history.tab.notifications', 'Notifications')}
            active={activeTab === ActiveTab.Notifications}
            onChangeTab={() => setQueryParams({ tab: ActiveTab.Notifications })}
          />
        </TabsBar>
      )}
      <TabContent className={styles.tabContent}>
        <Box paddingBottom={2}>
          <Text color="secondary" variant="body">
            {activeTab === ActiveTab.AlertEvents ? (
              <Trans i18nKey="alerting.central-alert-history.description.alert-events">
                View a history of all alert events generated by your Grafana-managed alert rules. All alert events are
                displayed regardless of whether silences or mute timings are set.
              </Trans>
            ) : (
              <Trans i18nKey="alerting.central-alert-history.description.notifications">
                View a history of all notifications sent from your Grafana-managed alert rules.
              </Trans>
            )}
          </Text>
        </Box>
        {activeTab === ActiveTab.AlertEvents && <CentralAlertHistoryScene />}
        {activeTab === ActiveTab.Notifications && notificationsEnabled && <NotificationsScene />}
      </TabContent>
    </AlertingPageWrapper>
  );
}

const getStyles = (theme: GrafanaTheme2) => ({
  tabContent: css({
    marginTop: theme.spacing(2),
  }),
});

export default withPageErrorBoundary(HistoryPage);
