<template>
  <div>
    <Input
      v-model="searchText"
      :placeholder="$t('SEARCH_CATEOGRY_NAME')"
      clearable
      style="margin-bottom: 16px"
      @on-change="onSearch"
    />
    <Tree
      :data="displayedTreeData"
      :show-checkbox="false"
      :highlight-current="false"
      :render="renderContent"
      :default-expand-all="true"
      :checked-keys.sync="checkedKeys"
    />
  </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 scoped>
</style>
