import React, { useEffect, useState } from 'react';
import { css } from '@emotion/css';
import { getDataSourceSrv } from '@grafana/runtime';
import {
  Alert,
  AlertVariant,
  Button,
  Field,
  Form,
  Icon,
  InlineField,
  Input,
  InputControl,
  Label,
  Modal,
  RelativeTimeRangePicker,
  Switch,
  useStyles2,
} from '@grafana/ui';
import {
  DataQuery,
  DataSourceInstanceSettings,
  getDefaultRelativeTimeRange,
  GrafanaTheme2,
  ScopedVars,
  VariableModel,
} from '@grafana/data';
import { IdDataQuery, RecordedQuery, AccessControlAction, EnterpriseStoreState } from '../types';
import { saveRecordedQuery, testRecordedQuery } from './state/actions';
import { getVariables } from 'app/features/variables/state/selectors';
import { connect, ConnectedProps } from 'react-redux';
import { hasOptions } from 'app/features/variables/guard';
import { variableAdapters } from 'app/features/variables/adapters';
import { VariableHide } from 'app/features/variables/types';
import { timeIntervals, TimeSelect } from './TimeSelect';
import { QueryOperationAction } from 'app/core/components/QueryOperationRow/QueryOperationAction';
import { getModalStyles } from '@grafana/ui/src/components/Modal/getModalStyles';
import { LicenseToken } from '../licensing/types';
import { getLicenseToken } from '../licensing/state/api';
import { contextSrv } from 'app/core/core';

function mapStateToProps(state: EnterpriseStoreState) {
  return {
    variables: getVariables(state),
  };
}

interface OwnProps {
  query?: DataQuery;
  queries?: Array<Partial<DataQuery>>;
  onAddQuery?: (query: DataQuery) => void;
  onChangeDataSource?: (ds: DataSourceInstanceSettings) => void;
  dataSource?: DataSourceInstanceSettings;
}

const connector = connect(mapStateToProps);
export type Props = ConnectedProps<typeof connector> & OwnProps;

const DocLink = (props: { href: string }) => {
  const styles = useStyles2(getStyles);
  return (
    <a href={props.href} className={styles.docsLink} target="_blank" rel="noreferrer">
      <Icon name="info-circle" />
    </a>
  );
};

interface SaveAddRecordedQuery {
  name: string;
  description: string;
  aggregationType: string;
  interval: number;
  range: number;
  isCount: boolean;
}

export const CreateRecordedQueryUnconnected = ({ query, queries, dataSource, variables: propVariables }: Props) => {
  const [isOpen, setIsOpen] = useState(false);
  const [token, setToken] = useState<LicenseToken | undefined>();
  const [alertSeverity, setAlertSeverity] = useState<AlertVariant>('info');
  const [alertMessage, setAlertMessage] = useState('');
  const modalStyles = useStyles2(getModalStyles);
  const styles = useStyles2(getStyles);

  useEffect(() => {
    const setTokenIfAccess = async () => {
      if (contextSrv.hasAccess(AccessControlAction.LicensingRead, contextSrv.isGrafanaAdmin)) {
        setToken(await getLicenseToken().catch(() => undefined));
      }
    };
    setTokenIfAccess();
  }, []);

  const closeModal = () => {
    setAlertMessage('');
    setAlertSeverity('info');
    setIsOpen(false);
  };

  const getRecordedQuery = async (data: SaveAddRecordedQuery) => {
    try {
      return await toRecordedQuery(data, variables);
    } catch (error) {
      setAlertSeverity('error');
      setAlertMessage(error.data.message);
      return;
    }
  };

  const submitForm = async (data: SaveAddRecordedQuery) => {
    const rq = await getRecordedQuery(data);
    if (!rq) {
      return;
    }

    saveRecordedQuery(rq)
      .then(() => {
        setAlertSeverity('success');
        setAlertMessage('Your new recorded query is recording successfully!');
      })
      .catch((error) => {
        setAlertSeverity('error');
        setAlertMessage(`Result: ${error.data.message}`);
      });
  };

  const submitTest = async (data: SaveAddRecordedQuery) => {
    const rq = await getRecordedQuery(data);
    if (!rq) {
      return;
    }

    testRecordedQuery(rq)
      .then((value) => {
        setAlertSeverity('info');
        setAlertMessage(`Result: ${value.data.message}`);
      })
      .catch((error) => {
        setAlertSeverity('error');
        setAlertMessage(error.data.message);
      });
  };

  const toRecordedQuery = async (data: SaveAddRecordedQuery, scopedVars: ScopedVars | {}): Promise<RecordedQuery> => {
    const rq = {
      target_ref_id: query ? query.refId : '',
      name: data.name,
      description: data.description,
      interval: data.interval,
      range: data.range,
      count: data.isCount,
      active: true,
    } as RecordedQuery;
    const queriesWithVars = queries?.map(async (q) => {
      const dataSourceName = q.datasource || dataSource?.name;
      const ds = await getDataSourceSrv().get(dataSourceName);
      const interpolatedTarget = ds.interpolateVariablesInQueries
        ? ds.interpolateVariablesInQueries([q as DataQuery], { ...scopedVars })[0]
        : q;

      const idQ = interpolatedTarget as IdDataQuery;
      idQ.datasourceId = ds ? ds.id : -1;
      return idQ;
    });
    rq.queries = queriesWithVars ? await Promise.all(queriesWithVars) : [];
    return rq;
  };

  const variables = propVariables?.filter((variable) => variable.hide !== VariableHide.hideVariable);
  const title = (
    <h2 className={modalStyles.modalHeaderTitle}>
      Create recorded query
      <DocLink href="https://grafana.com/docs/grafana/latest/enterprise/recorded-queries/#create-a-recorded-query" />
    </h2>
  );

  const syncButton =
    alertSeverity !== 'success' ? (
      <div aria-label="Test the recorded query">
        <Icon name="sync" />
      </div>
    ) : undefined;

  const doneButton =
    alertSeverity === 'success' ? (
      <Button type="button" variant="primary" onClick={closeModal} aria-label="Close recording query button">
        Close
      </Button>
    ) : (
      <Button
        type="button"
        variant="secondary"
        onClick={closeModal}
        fill="outline"
        aria-label="Cancel recording query button"
      >
        Cancel
      </Button>
    );

  return (
    <>
      <QueryOperationAction
        title="Create recorded query"
        icon="record-audio"
        onClick={() => {
          setIsOpen(true);
        }}
      />
      <Modal isOpen={isOpen} title={title} onDismiss={closeModal} className={styles.modal}>
        <Form onSubmit={submitForm} validateOn="all">
          {({ register, errors, control, getValues }) => (
            <>
              <Field
                label="Name"
                description={'Give this query a name'}
                invalid={!!errors.name}
                error={errors.name?.message}
                required={true}
              >
                <Input
                  {...register('name', { required: { value: true, message: 'Name is required' } })}
                  id="add-recorded-query-name"
                  autoFocus
                />
              </Field>
              <Field label="Description" description={'Provide a description for this query'}>
                <Input {...register('description')} id="add-recorded-query-desc" />
              </Field>
              <div className={styles.timeSelect}>
                <InputControl
                  name="interval"
                  control={control}
                  defaultValue={timeIntervals[0].value}
                  render={({ field: { ref, value, onChange, ...field } }) => {
                    return (
                      <TimeSelect
                        label={'Interval'}
                        description={'Decide how often to record this query'}
                        value={value}
                        onChange={onChange}
                      />
                    );
                  }}
                />
              </div>
              <div className={styles.timeSelect}>
                <InputControl
                  name="range"
                  control={control}
                  defaultValue={getDefaultRelativeTimeRange().from}
                  render={({ field: { ref, value, onChange, ...field } }) => {
                    const desc = (
                      <>
                        {"Select this query's relative time range"}
                        <DocLink href="https://grafana.com/docs/grafana/latest/dashboards/time-range-controls/#time-units-and-relative-ranges" />
                      </>
                    );
                    const label = <Label description={desc}>Relative Time Range *</Label>;
                    return (
                      <Field label={label} invalid={!!errors.range} error={errors.name?.message} required={true}>
                        <RelativeTimeRangePicker
                          timeRange={{ from: value, to: 0 }}
                          onChange={(r) => onChange(r.from)}
                        />
                      </Field>
                    );
                  }}
                />
              </div>
              {variables?.length > 0 ? (
                <Field label="Template variables" description="Select a value for each template variable">
                  <>
                    {variables.map((variable) => {
                      const { picker: Picker, setValue } = variableAdapters.get(variable.type);
                      return (
                        <InlineField label={variable.name} key={variable.name} labelWidth={16}>
                          <Picker
                            onVariableChange={(updated: VariableModel) => {
                              if (hasOptions(updated)) {
                                setValue(updated, updated.current);
                              }
                            }}
                            variable={variable}
                          />
                        </InlineField>
                      );
                    })}
                  </>
                </Field>
              ) : null}
              <Field
                label="Count query results"
                description={
                  <>
                    {'Count the rows returned from this query'}
                    <DocLink href="https://grafana.com/docs/grafana/latest/enterprise/recorded-queries/#create-a-recorded-query" />
                  </>
                }
              >
                <Switch {...register('isCount')} id="add-recorded-query-count" />
              </Field>
              <Alert
                className={styles.testQuery}
                severity={alertSeverity}
                title={alertSeverity === 'success' ? alertMessage : 'Test this recorded query'}
                buttonContent={syncButton}
                onRemove={alertSeverity !== 'success' ? () => submitTest(getValues()) : undefined} // undefined ensures no 'x' button
              >
                <>{alertSeverity !== 'success' && alertMessage}</>
                {alertMessage === 'An unknown issue is preventing the system from processing your query.' &&
                  contactSupportMessage(token)}
              </Alert>
              <Modal.ButtonRow>
                {doneButton}
                {alertSeverity !== 'success' && (
                  <Button type="submit" aria-label="Start recording query button">
                    Start recording query
                  </Button>
                )}
              </Modal.ButtonRow>
            </>
          )}
        </Form>
      </Modal>
    </>
  );
};

const contactSupportMessage = (token?: LicenseToken) => {
  let href = 'https://grafana.com/contact';
  if (token && token.slug && token.lid) {
    href = `https://grafana.com/orgs/${token.slug}/tickets?support=licensing&licenseId=${token.lid}`;
  }

  return (
    <>
      To submit a support ticket to Grafana Labs, complete the <a href={href}>Contact Grafana Labs</a>
    </>
  );
};

const getStyles = (theme: GrafanaTheme2) => {
  return {
    modal: css`
      width: 550px;
    `,
    testQuery: css`
      margin-top: ${theme.spacing(3)};
    `,
    timeSelect: css`
      width: 50%;
    `,
    docsLink: css`
      margin-left: ${theme.spacing(0.5)};
    `,
  };
};

export const CreateRecordedQuery = connector(CreateRecordedQueryUnconnected);
