<template>
  <div class="tk-cat-tree">
    <div class="tk-cat-tree__search">
      <Input
        v-model="searchText"
        :placeholder="$t('SEARCH_CATEOGRY_NAME')"
        clearable
        @on-change="onSearch"
      />
    </div>
    <div class="tk-cat-tree__body">
      <Tree
        :data="displayedTreeData"
        :show-checkbox="false"
        :highlight-current="false"
        :render="renderContent"
        :default-expand-all="true"
        :checked-keys.sync="checkedKeys"
      />
    </div>
  </div>
</template>

<script>
import { getTiktokCategorySeller } from '@/api/tiktok/client/category';
import slugify from 'slugify';

export default {
  name: 'TiktokCategoryTree',
  data() {
    return {
      flatData: [],
      fullTreeData: [],
      displayedTreeData: [],
      searchText: '',
      checkedKeys: [],
      matchedKeys: [],
    };
  },
  methods: {
    buildTree(data) {
      const idMap = {};
      data.forEach((item) => {
        idMap[item.id] = {
          key: item.id,
          category_id: item.id,
          title: item.local_display_name,
          name: item.local_display_name,
          slug: slugify(item.local_display_name, {
            lower: true,
            trim: true,
            locale: 'vi',
          }),
          isLeaf: item.is_leaf,
          image: item.image || null,
          children: [],
        };
      });
      const tree = [];
      data.forEach((item) => {
        const node = idMap[item.id];
        if (item.parent_id === '0' || item.parent_id === 0 || item.parent_id === null) {
          tree.push(node);
        } else {
          const parent = idMap[item.parent_id];
          if (parent) {
            parent.children.push(node);
          }
        }
      });
      return tree;
    },
    searchTreeForHighlight(treeNodes, keyword, matches = []) {
      treeNodes.forEach((node) => {
        if (node.title.toLowerCase().includes(keyword.toLowerCase())) {
          matches.push(node.category_id);
        }
        if (node.children && node.children.length) {
          this.searchTreeForHighlight(node.children, keyword, matches);
        }
      });
      return matches;
    },
    filterTree(treeNodes, keyword) {
      const filtered = [];
      treeNodes.forEach((node) => {
        const titleMatch = node.title.toLowerCase().includes(keyword.toLowerCase());
        let childrenFiltered = [];
        if (node.children && node.children.length) {
          childrenFiltered = this.filterTree(node.children, keyword);
        }
        if (titleMatch) {
          filtered.push({
            ...node,
            children: node.children,
          });
        } else if (childrenFiltered.length) {
          filtered.push({
            ...node,
            children: childrenFiltered,
          });
        }
      });
      return filtered;
    },
    onSearch() {
      const keyword = this.searchText.trim();
      if (!keyword) {
        this.matchedKeys = [];
        this.displayedTreeData = this.fullTreeData;
      } else {
        const matches = this.searchTreeForHighlight(this.fullTreeData, keyword, []);
        this.matchedKeys = matches;
        this.displayedTreeData = this.filterTree(this.fullTreeData, keyword);
      }
    },
    renderContent(h, { data }) {
      const { category_id: categoryId, slug } = data;

      const isMatched = this.matchedKeys.includes(categoryId);
      const thumbnail = data.image;

      const spyUrl = this.getRouterUrl(`/tiktok/spy/category/${categoryId}`);
      const categoryUrl = `https://shop-vn.tiktok.com/c/${slug}/${categoryId}`;

      const attrMatch = isMatched
        ? { color: '#f90', fontWeight: 'bold' }
        : {};
      return h(
        'div',
        {
          style: {
            display: 'flex',
            alignItems: 'center',
          },
        },
        [
          thumbnail
            && h('img', {
              attrs: { src: thumbnail },
              style: {
                width: '24px',
                height: '24px',
                marginRight: '8px',
                borderRadius: '4px',
                objectFit: 'cover',
              },
            }),
          h(
            'a',
            {
              attrs: {
                href: categoryUrl,
                target: '_blank',
              },
              style: { textDecoration: 'none', color: '#515a6e', ...attrMatch },
            },
            data.title,
          ),
          h(
            'a',
            {
              attrs: { href: spyUrl, target: '_blank' },
              style: { marginLeft: '5px' },
            },
            this.$t('SPY_BTN'),
          ),
        ],
      );
    },
  },
  created() {
    this.flatData = getTiktokCategorySeller();
    this.fullTreeData = this.buildTree(this.flatData);
    this.displayedTreeData = this.fullTreeData;
  },
};
</script>

<style lang="scss" scoped>
@import '@/vue/styles/tokens.scss';

.tk-cat-tree {
  @include card(16px);

  display: flex;
  flex-direction: column;
  gap: 12px;
  border: 1px solid $c-border;
  color: $c-text;

  &__search {
    position: sticky;
    top: 0;
    z-index: 2;
    background: $c-surface;
    padding-bottom: 4px;
  }

  &__body {
    @include scrollbar;

    max-height: 70vh;
    overflow-y: auto;
    padding-right: 4px;
  }
}

.tk-cat-tree ::v-deep {
  .ivu-input {
    border-radius: $radius-item;
    border-color: $c-border-input;
    transition: border-color $motion-fast, box-shadow $motion-fast;
  }

  .ivu-input::placeholder {
    color: $c-text-placeholder;
  }

  .ivu-tree ul li {
    margin: 2px 0;
  }

  .ivu-tree-title {
    display: block;
    padding: 4px 8px;
    border-radius: $radius-item;
    color: $c-text;
    background: transparent;
    transition: background $motion-fast, color $motion-fast;

    &:hover {
      background: $c-surface-alt;
    }
  }

  .ivu-tree-title-selected,
  .ivu-tree-title-selected:hover {
    background: $c-brand-tint;
    color: $c-text-strong;
  }

  .ivu-tree-arrow {
    color: $c-text-muted;
    transition: color $motion-fast;

    &:hover {
      color: $c-brand;
    }
  }

  .ivu-tree-title a {
    transition: color $motion-fast;

    &:hover {
      color: $c-brand;
    }
  }
}
</style>
