<template>
  <div class="sv-picker">
    <Input
      v-model="query"
      :placeholder="$t('SHOPEE_VIDEO_PICKER_SEARCH')"
      search
      class="sv-picker__search"
      @on-search="onSearch"
    />

    <div class="sv-picker__meta">
      <span>{{ $t('SHOPEE_VIDEO_PICKER_MAX', { max: maxProducts }) }}</span>
      <span class="sv-picker__count">{{ value.length }}/{{ maxProducts }}</span>
    </div>

    <div
      v-if="value.length"
      class="sv-picker__selected"
    >
      <Tag
        v-for="product in value"
        :key="product.itemId"
        closable
        color="primary"
        @on-close="removeProduct(product)"
      >
        {{ product.name }}
      </Tag>
    </div>

    <div class="sv-picker__list">
      <div
        v-if="loading"
        class="sv-picker__loading"
      >
        <Spin />
      </div>

      <p
        v-else-if="!items.length"
        class="sv-picker__empty"
      >
        {{ $t('SHOPEE_VIDEO_PICKER_EMPTY') }}
      </p>

      <div
        v-for="item in items"
        v-else
        :key="item.itemId"
        class="sv-picker__item"
        :class="{ 'is-selected': isSelected(item) }"
        @click="toggleProduct(item)"
      >
        <div class="sv-picker__thumb">
          <img
            :src="item.coverUrl"
            alt=""
            @error="onImgError"
          >
        </div>
        <div class="sv-picker__info">
          <span class="sv-picker__name">{{ item.name }}</span>
          <span class="sv-picker__sub">
            <span
              v-if="item.priceText"
              class="sv-picker__price"
            >{{ item.priceText }}</span>
            <span class="sv-picker__stock">{{ $t('SHOPEE_VIDEO_PICKER_STOCK', { stock: item.snapshot.stock }) }}</span>
          </span>
        </div>
        <Icon
          v-if="isSelected(item)"
          type="md-checkmark-circle"
          class="sv-picker__check"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent } from '@vue/composition-api';
import { getVideoItemList } from '@/api/shopee/seller/video';
import { imageUrl } from '@/adapter/shopee/render/utils';
import { loggerShopee } from '@/plugins/logger';

const MAX_PRODUCTS = 6;

export default defineComponent({
  props: {
    value: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      query: '',
      items: [],
      loading: false,
      maxProducts: MAX_PRODUCTS,
    };
  },
  created() {
    this.loadItems('');
  },
  methods: {
    formatPrice(minPrice, maxPrice) {
      if (!minPrice) {
        return '';
      }

      const min = Math.round(minPrice);
      const max = Math.round(maxPrice);

      if (max && max !== min) {
        return `${min.toLocaleString('vi-VN')}đ - ${max.toLocaleString('vi-VN')}đ`;
      }

      return `${min.toLocaleString('vi-VN')}đ`;
    },
    async loadItems(itemName) {
      this.loading = true;

      try {
        const result = await getVideoItemList(1, 20, itemName || '');
        this.items = (result.items || []).map((item) => {
          return {
            itemId: `${item.itemId}`,
            name: item.name || '',
            cover: item.cover || '',
            coverUrl: imageUrl(item.cover || ''),
            priceText: this.formatPrice(item.minPrice || 0, item.maxPrice || 0),
            snapshot: {
              minPrice: item.minPrice || 0,
              maxPrice: item.maxPrice || 0,
              stock: item.stock || 0,
              status: item.status || 0,
            },
          };
        });
      } catch (error) {
        loggerShopee.error({
          msg: 'SHOPEE_VIDEO_PICKER_LOAD_ERROR',
          error,
        });
        this.items = [];
      }

      this.loading = false;
    },
    onSearch() {
      this.loadItems(this.query);
    },
    onImgError(event) {
      event.target.classList.add('is-hidden');
    },
    isSelected(item) {
      return this.value.some((product) => product.itemId === `${item.itemId}`);
    },
    toggleProduct(item) {
      if (this.isSelected(item)) {
        this.removeProduct(item);
        return;
      }

      if (this.value.length >= MAX_PRODUCTS) {
        this.$Message.warning(this.$t('SHOPEE_VIDEO_PICKER_MAX', { max: MAX_PRODUCTS }));
        return;
      }

      const picked = {
        itemId: item.itemId,
        name: item.name,
        cover: item.cover,
        snapshot: item.snapshot,
      };

      const next = this.value.concat([picked]);
      this.$emit('input', next);
    },
    removeProduct(item) {
      const next = this.value.filter((product) => product.itemId !== `${item.itemId}`);
      this.$emit('input', next);
    },
  },
});
</script>

<style lang="scss" scoped>
.sv-picker {
  &__search {
    margin-bottom: 8px;
  }

  &__meta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    color: #8a8f99;
    margin-bottom: 8px;
  }

  &__count {
    font-weight: 600;
    color: #ee4d2d;
  }

  &__selected {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    margin-bottom: 8px;
  }

  &__list {
    max-height: 280px;
    overflow-y: auto;
    border: 1px solid #eef0f3;
    border-radius: 10px;
    padding: 4px;
  }

  &__loading,
  &__empty {
    text-align: center;
    color: #b0b4bb;
    padding: 24px 0;
    font-size: 13px;
  }

  &__item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px;
    border-radius: 8px;
    cursor: pointer;
    transition: background 0.12s ease;

    &:hover {
      background: #f7f8fa;
    }

    &.is-selected {
      background: #fff3f0;
    }
  }

  &__thumb {
    width: 44px;
    height: 44px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;
    background: #eef0f3;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;

      &.is-hidden {
        display: none;
      }
    }
  }

  &__info {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  &__name {
    font-size: 13px;
    color: #2d2f33;
    line-height: 1.35;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  &__sub {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 12px;
  }

  &__price {
    color: #ee4d2d;
    font-weight: 600;
  }

  &__stock {
    color: #9aa0a8;
  }

  &__check {
    color: #ee4d2d;
    font-size: 20px;
    flex-shrink: 0;
  }
}
</style>
