import GlBadge from '../components/base/badge/badge';
import GlButton from '../components/base/button/button';
import GlCollapsibleListbox from '../components/base/new_dropdowns/listbox/listbox';
import GlFormInput from '../components/base/form/form_input/form_input';
import GlLink from '../components/base/link/link';
import GlTable from '../components/base/table/table';
import { GlTooltipDirective } from '../directives/tooltip';
import TOKENS_DEFAULT from './build/json/tokens.json';
import TOKENS_DARK from './build/json/tokens.dark.json';
import __vue_normalize__ from 'vue-runtime-helpers/dist/normalize-component.js';

var script = {
  name: 'TokensTable',
  TOKENS_DEFAULT,
  TOKENS_DARK,
  components: {
    GlBadge,
    GlButton,
    GlCollapsibleListbox,
    GlFormInput,
    GlLink,
    GlTable
  },
  directives: {
    GlTooltip: GlTooltipDirective
  },
  fields: [{
    key: 'description',
    label: 'Description'
  }, {
    key: 'value',
    label: 'Value'
  }],
  data() {
    return {
      filter: null,
      platforms: [{
        value: 'name',
        text: 'Name'
      }, {
        value: 'figma',
        text: 'Figma'
      }, {
        value: 'css',
        text: 'CSS'
      }, {
        value: 'scss',
        text: 'SCSS'
      }],
      modes: [{
        value: 'default',
        text: 'Default'
      }, {
        value: 'dark',
        text: 'Dark'
      }],
      selectedPlatform: 'name',
      selectedMode: 'default',
      tokens: {
        default: this.$options.TOKENS_DEFAULT,
        dark: this.$options.TOKENS_DARK
      }
    };
  },
  computed: {
    items() {
      return this.transformTokensToTableRows(this.tokens[this.selectedMode]);
    }
  },
  methods: {
    isColor(type) {
      return type === 'color';
    },
    isAliasValue(value) {
      return typeof value === 'string' && value.includes('{');
    },
    isAliasObject(value) {
      return typeof value === 'object' && Object.values(value).some(val => this.isAliasValue(val));
    },
    getAliasValueName(value) {
      if (this.isAliasValue(value)) {
        return value.slice(1, -1);
      }
      return value;
    },
    getValueLabel(token) {
      const {
        value
      } = token.original;
      if (this.isAliasObject(value)) {
        return this.getAliasValueName(value[this.selectedMode]);
      }
      if (this.isAliasValue(value)) {
        return this.getAliasValueName(value);
      }
      return token.value;
    },
    transformTokenToTableColumns(token) {
      return {
        id: token.path.filter(Boolean).join('-'),
        name: this.formatTokenName(this.selectedPlatform, token),
        type: token.$type,
        value: token.value,
        valueLabel: this.getValueLabel(token),
        deprecated: token.deprecated,
        description: token.comment
      };
    },
    transformTokensToTableRows(tokens) {
      const tokensArray = [];
      Object.keys(tokens).forEach(key => {
        const token = tokens[key];
        if (token.value) {
          tokensArray.push(this.transformTokenToTableColumns(token));
        } else {
          tokensArray.push(...this.transformTokensToTableRows(token));
        }
      });
      tokensArray
      // Sort tokensArray by id
      .sort((a, b) => {
        if (a.id < b.id) {
          return -1;
        }
        if (a.id > b.id) {
          return 1;
        }
        return 0;
      })
      // Sort tokensArray so deprecated items are last
      .sort((a, b) => {
        if (a.deprecated && !b.deprecated) {
          return 1;
        }
        if (!a.deprecated && b.deprecated) {
          return -1;
        }
        return 0;
      });
      return tokensArray;
    },
    formatTokenName(format, token) {
      let figmaPrefix = '';
      const prefix = token.prefix === false ? '' : 'gl';
      switch (format) {
        case 'figma':
          if (token.filePath.match('contextual')) {
            figmaPrefix = '🔒/';
          }
          if (token.deprecated) {
            figmaPrefix = '⚠️ DEPRECATED/';
          }
          return `${figmaPrefix}${token.path.filter(Boolean).join('-')}`;
        case 'css':
          return `var(--${[prefix, ...token.path].filter(Boolean).join('-')})`;
        case 'scss':
          return `$${[prefix, ...token.path].filter(Boolean).join('-')}`;
        default:
          return token.path.filter(Boolean).join('.');
      }
    },
    getTokenName(token) {
      return `$${token.prefix === false ? '' : 'gl-'}${token.path.filter(Boolean).join('-')}`;
    },
    copyToClipboard(value) {
      navigator.clipboard.writeText(value);
    }
  }
};

/* script */
const __vue_script__ = script;

/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',[_c('p',{staticClass:"gl-text-sm gl-text-subtle"},[_vm._v("\n    For full token details, see\n    "),_c('gl-link',{attrs:{"href":"https://gitlab.com/gitlab-org/gitlab-ui/-/tree/main/src/tokens/build/json","target":"_blank"}},[_vm._v("https://gitlab.com/gitlab-org/gitlab-ui/-/tree/main/src/tokens/build/json")])],1),_vm._v(" "),_c('div',{staticClass:"gl-mb-5 gl-flex gl-items-center gl-gap-3"},[_c('gl-form-input',{attrs:{"placeholder":"Type to search"},model:{value:(_vm.filter),callback:function ($$v) {_vm.filter=$$v;},expression:"filter"}}),_vm._v(" "),_c('gl-collapsible-listbox',{attrs:{"selected":_vm.selectedPlatform,"items":_vm.platforms},on:{"search":function($event){_vm.query = $event;}},model:{value:(_vm.selectedPlatform),callback:function ($$v) {_vm.selectedPlatform=$$v;},expression:"selectedPlatform"}}),_vm._v(" "),_c('gl-collapsible-listbox',{attrs:{"selected":_vm.selectedMode,"items":_vm.modes},on:{"search":function($event){_vm.query = $event;}},model:{value:(_vm.selectedMode),callback:function ($$v) {_vm.selectedMode=$$v;},expression:"selectedMode"}})],1),_vm._v(" "),_c('gl-table',{attrs:{"filter":_vm.filter,"items":_vm.items,"fields":_vm.$options.fields,"tbody-tr-attr":function (item) { return ({ id: item.id }); },"hover":"","stacked":"sm"},scopedSlots:_vm._u([{key:"cell(description)",fn:function(ref){
var ref_item = ref.item;
var name = ref_item.name;
var deprecated = ref_item.deprecated;
var description = ref_item.description;
return [_c('code',{staticClass:"gl-text-base gl-text-strong"},[_vm._v("\n        "+_vm._s(name)+"\n        "),_c('gl-button',{directives:[{name:"gl-tooltip",rawName:"v-gl-tooltip"}],attrs:{"title":("Copy " + _vm.selectedPlatform + " value to clipboard"),"icon":"copy-to-clipboard","aria-label":("Copy " + _vm.selectedPlatform + " value to clipboard"),"size":"small"},on:{"click":function($event){return _vm.copyToClipboard(name)}}})],1),_vm._v(" "),(deprecated)?_c('gl-badge',{attrs:{"variant":"danger"}},[_vm._v("Deprecated")]):_vm._e(),_vm._v(" "),(description)?_c('div',{staticClass:"gl-mt-3 gl-text-subtle"},[_vm._v("\n        "+_vm._s(description)+"\n      ")]):_vm._e()]}},{key:"cell(value)",fn:function(ref){
var ref_item = ref.item;
var type = ref_item.type;
var value = ref_item.value;
var valueLabel = ref_item.valueLabel;
return [_c('div',{staticClass:"gl-flex gl-items-center gl-gap-3"},[(_vm.isColor(type))?_c('div',{staticClass:"gl-h-5 gl-w-5 gl-rounded-base",style:({ 'background-color': value })}):_vm._e(),_vm._v(" "),_c('code',{staticClass:"gl-text-base gl-text-strong"},[_vm._v(_vm._s(valueLabel))])])]}}])})],1)};
var __vue_staticRenderFns__ = [];

  /* style */
  const __vue_inject_styles__ = undefined;
  /* scoped */
  const __vue_scope_id__ = undefined;
  /* module identifier */
  const __vue_module_identifier__ = undefined;
  /* functional template */
  const __vue_is_functional_template__ = false;
  /* style inject */
  
  /* style inject SSR */
  
  /* style inject shadow dom */
  

  
  const __vue_component__ = __vue_normalize__(
    { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
    __vue_inject_styles__,
    __vue_script__,
    __vue_scope_id__,
    __vue_is_functional_template__,
    __vue_module_identifier__,
    false,
    undefined,
    undefined,
    undefined
  );

export default __vue_component__;
