import {Fragment, useCallback} from 'react';

import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
import Alert from 'sentry/components/alert';
import Panel from 'sentry/components/panels/panel';
import PanelBody from 'sentry/components/panels/panelBody';
import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
import {t} from 'sentry/locale';
import type {MetricsExtractionRule} from 'sentry/types/metrics';
import type {Project} from 'sentry/types/project';
import {hasCustomMetricsExtractionRules} from 'sentry/utils/metrics/features';
import routeTitleGen from 'sentry/utils/routeTitle';
import {useNavigate} from 'sentry/utils/useNavigate';
import useOrganization from 'sentry/utils/useOrganization';
import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
import TextBlock from 'sentry/views/settings/components/text/textBlock';
import {
  createCondition,
  explodeAggregateGroup,
  type FormData,
  MetricsExtractionRuleForm,
} from 'sentry/views/settings/projectMetrics/metricsExtractionRuleForm';
import {useCreateMetricsExtractionRules} from 'sentry/views/settings/projectMetrics/utils/api';

const INITIAL_DATA: FormData = {
  spanAttribute: null,
  aggregates: ['count'],
  tags: ['release', 'environment'],
  conditions: [createCondition()],
};

const PAGE_TITLE = t('Configure Metric');

function ExtractMetric({project}: {project: Project}) {
  const navigate = useNavigate();
  const organization = useOrganization();
  const createExtractionRuleMutation = useCreateMetricsExtractionRules(
    organization.slug,
    project.slug
  );

  const handleSubmit = useCallback(
    (
      formData: FormData,
      onSubmitSuccess: (data: FormData) => void,
      onSubmitError: (error: any) => void
    ) => {
      const data = formData as FormData;

      const extractionRule: MetricsExtractionRule = {
        spanAttribute: data.spanAttribute!,
        tags: data.tags,
        aggregates: data.aggregates.flatMap(explodeAggregateGroup),
        unit: 'none',
        conditions: data.conditions,
      };

      createExtractionRuleMutation.mutate(
        {
          metricsExtractionRules: [extractionRule],
        },
        {
          onSuccess: () => {
            onSubmitSuccess(data);
            addSuccessMessage(t('Metric extraction rule created'));
            navigate(-1);
          },
          onError: error => {
            const message = error?.responseJSON?.detail
              ? (error.responseJSON.detail as string)
              : t('Unable to save your changes.');
            onSubmitError(message);
            addErrorMessage(message);
          },
        }
      );
      onSubmitSuccess(data);
    },
    [createExtractionRuleMutation, navigate]
  );

  if (!hasCustomMetricsExtractionRules(organization)) {
    return <Alert type="warning">{t("You don't have access to this feature")}</Alert>;
  }

  return (
    <Fragment>
      <SentryDocumentTitle title={routeTitleGen(PAGE_TITLE, project.slug, false)} />
      <SettingsPageHeader title={PAGE_TITLE} />
      <TextBlock>{t('Configure tracking of span attributes as metrics.')}</TextBlock>
      <Panel>
        <PanelBody>
          <MetricsExtractionRuleForm
            project={project}
            initialData={INITIAL_DATA}
            onCancel={() => navigate(-1)}
            submitLabel={t('Confirm')}
            onSubmit={handleSubmit}
            requireChanges
          />
        </PanelBody>
      </Panel>
    </Fragment>
  );
}

export default ExtractMetric;
