import { FieldNamePicker } from '../../grafana/MatchersUI/FieldNamePicker';

import { GrafanaTheme, StandardEditorProps } from '@grafana/data';
import {
  Button,
  ColorPicker,
  HorizontalGroup,
  IconButton,
  InlineField,
  InlineSwitch,
  Input,
  stylesFactory,
  ThemeContext,
} from '@grafana/ui';

import React from 'react';

import { css } from 'emotion';
import * as _ from 'lodash';

interface Props {
  defaultColor: string;
  arcBackground: string;
  thresholds: ThresholdConfig[];
}

type ThresholdConfig = {
  color: string;
  useMetric: boolean;
  value?: number;
  metricName?: string;
};

const DEFAULT_THRESHOLD: ThresholdConfig = {
  color: '#378372d',
  useMetric: false,
  value: 0,
};

const fieldNamePickerSettings = {
  settings: { width: 24 },
} as any;

export function ThresholdsEditor({ onChange, value, context }: StandardEditorProps<Props>) {
  const config = value;

  const addThreshold = () => {
    config.thresholds.push(_.cloneDeep(DEFAULT_THRESHOLD));
    onChange(config);
  };

  const removeThreshold = (idx: number) => {
    config.thresholds.splice(idx, 1);
    onChange(config);
  };

  const onFieldChange = (field: keyof Props, value: any) => {
    config[field] = value;
    onChange(config);
  };

  const onThresholdFieldChange = (thresholdIdx: number, field: keyof ThresholdConfig, value: any) => {
    // @ts-ignore
    config.thresholds[thresholdIdx][field] = value;
    onChange(config);
  };

  return (
    <ThemeContext.Consumer>
      {(theme) => {
        const styles = getStyles(theme.v1);
        return (
          <div>
            <Input
              className={styles.row}
              type="text"
              value={'Default Gauge Color'}
              disabled
              prefix={
                <div>
                  <ColorPicker
                    color={config.defaultColor}
                    onChange={(val) => onFieldChange('defaultColor', val)}
                    enableNamedColors={true}
                  />
                </div>
              }
            />
            <Input
              className={styles.row}
              type="text"
              value={'Arc Background'}
              disabled
              prefix={
                <div>
                  <ColorPicker
                    color={config.arcBackground}
                    onChange={(val) => onFieldChange('arcBackground', val)}
                    enableNamedColors={true}
                  />
                </div>
              }
            />
            {config.thresholds.map((threshold, thresholdIdx) => {
              return (
                <HorizontalGroup key={thresholdIdx}>
                  <Input
                    type="text"
                    value={'Color'}
                    disabled
                    prefix={
                      <div>
                        <ColorPicker
                          color={threshold.color}
                          onChange={(newVal) => onThresholdFieldChange(thresholdIdx, 'color', newVal)}
                          enableNamedColors={true}
                        />
                      </div>
                    }
                  />
                  <InlineField label="Use metric">
                    <InlineSwitch
                      value={threshold.useMetric}
                      onChange={(evt) => onThresholdFieldChange(thresholdIdx, 'useMetric', (evt.target as any).checked)}
                    />
                  </InlineField>
                  {threshold.useMetric ? (
                    <FieldNamePicker
                      context={context}
                      value={threshold.metricName as string}
                      onChange={(newVal: any) => onThresholdFieldChange(thresholdIdx, 'metricName', newVal)}
                      item={fieldNamePickerSettings}
                    />
                  ) : (
                    <Input
                      placeholder="value"
                      value={threshold.value}
                      onChange={(evt) => onThresholdFieldChange(thresholdIdx, 'value', (evt.target as any).value)}
                    />
                  )}
                  <IconButton 
                    name="trash-alt" 
                    onClick={() => removeThreshold(thresholdIdx)}
                    tooltip="Delete Threshold"
                  ></IconButton>
                </HorizontalGroup>
              );
            })}
            <Button variant="secondary" onClick={addThreshold}>
              Add Threshold
            </Button>
          </div>
        );
      }}
    </ThemeContext.Consumer>
  );
}

interface ThresholdsEditorStyles {
  row: string;
}

const getStyles = stylesFactory((theme: GrafanaTheme): ThresholdsEditorStyles => {
  return {
    row: css`
      margin-bottom: ${theme.spacing.sm};
    `,
  };
});
