<template>
  <div class="wardrobe-assets flex">
    <aside class="wardrobe-assets__filters">
      <div class="filters-card">
        <div class="filters-card__heading">
          <h2 class="filters-card__title">{{ t('Wardrobe.assets.filters') }}</h2>
          <button class="filters-card__clear" type="button" @click="clearFilters">
            {{ t('Wardrobe.assets.clear') }}
          </button>
        </div>

        <section class="filter-group">
          <h3 class="filter-group__title">{{ t('Wardrobe.assets.categories') }}</h3>
          <div class="filter-group__line"></div>
          <div class="filter-group__options">
            <button
              v-for="option in categories"
              :key="option.value"
              class="filter-option"
              type="button"
              :class="{ 'is-active': isCategoryActive(option.value) }"
              @click="toggleCategory(option.value)"
            >
              <span class="filter-option__box">
                <span class="filter-option__tick"></span>
              </span>
              <span class="filter-option__label">{{ option.label }}</span>
            </button>
          </div>
        </section>

        <section class="filter-group">
          <h3 class="filter-group__title">{{ t('Wardrobe.assets.gender') }}</h3>
          <div class="filter-group__line"></div>
          <div class="filter-group__options">
            <button
              v-for="option in genders"
              :key="option.value"
              class="filter-option"
              type="button"
              :class="{ 'is-active': filters.gender === option.value }"
              @click="setGender(option.value)"
            >
              <span class="filter-option__box">
                <span class="filter-option__tick"></span>
              </span>
              <span class="filter-option__label">{{ option.label }}</span>
            </button>
          </div>
        </section>
      </div>
    </aside>

    <section
      class="wardrobe-assets__content flex flex-1 flex-col"
      :class="{ 'has-data': dataList.length }"
    >
      <div class="assets-toolbar">
        <div class="assets-toolbar__selection">
          <div class="select-count flex align-center">
            <img src="@/assets/images/wardrobe/select.png" />
            <span class="assets-toolbar__count">
              {{ t('Wardrobe.assets.selectedCount', { count: selectedCount }) }}
            </span>
          </div>
          <div class="assets-toolbar__link" @click="handleSelectAll(true)">
            {{ t('Wardrobe.assets.selectAll') }}
          </div>
          <div class="assets-toolbar__link" @click="handleSelectAll(false)">
            {{ t('Wardrobe.assets.deselectAll') }}
          </div>
        </div>

        <div class="assets-toolbar__actions">
          <div
            class="assets-toolbar__download flex flex-center"
            :class="{ disabled: selectedCount < 1 }"
            @click="handleDownloadSelected"
          >
            <SvgIcon name="downloadBtn" color="#fff" />
            <span>{{ t('Wardrobe.assets.downloadSelected') }}</span>
          </div>
        </div>
      </div>
      <div v-if="dataList.length" class="data-list-container">
        <div ref="dataListRef" class="data-list">
          <div
            v-for="(item, index) in dataList"
            :key="item.url"
            class="item"
            :class="{ 'is-last-column': isLastColumn(index) }"
          >
            <img
              v-show="item.checked"
              src="@/assets/images/wardrobe/checked.png"
              @click="handleSelectItem(item)"
              class="checkbox"
            />
            <div v-show="!item.checked" class="checkbox" @click="handleSelectItem(item)" />
            <CommodityItem
              download
              :url="item.url"
              :name="item.title"
              :price="item.price"
              :showPrice="false"
            ></CommodityItem>
          </div>
        </div>
      </div>

      <Empty v-else @explore="goToDigitalItems" />
    </section>
  </div>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { useClothesCategories } from '@/utils/ClothesCategory'
import img from '@/assets/images/collectionStory/Rectangle.png'
import Empty from './Empty.vue'

interface FilterOption {
  label: string
  value: string
}

const router = useRouter()
const { t } = useI18n({ useScope: 'global' })
const clothesCategories = useClothesCategories()

const categories = computed<FilterOption[]>(() => [
  { label: t('Wardrobe.common.all'), value: 'all' },
  ...clothesCategories.value.map((option) => ({
    label: option.label,
    value: option.value
  }))
])

const genders = computed<FilterOption[]>(() => [
  { label: t('Wardrobe.common.all'), value: 'all' },
  { label: t('Wardrobe.assets.genders.male'), value: 'male' },
  { label: t('Wardrobe.assets.genders.female'), value: 'female' }
])

const categoryValues = computed(() =>
  categories.value.filter((option) => option.value !== 'all').map((option) => option.value)
)

const filters = reactive({
  categories: ['skirt'] as string[],
  gender: 'all'
})

const dataList = ref([
  {
    url: img,
    title: 'Windswept Burden',
    price: '$100.00',
    checked: false
  },
  {
    url: img,
    title: 'Windswept Burden',
    price: '$100.00',
    checked: false
  },
  {
    url: img,
    title: 'Windswept Burden',
    price: '$100.00',
    checked: false
  },
  {
    url: img,
    title: 'Windswept Burden',
    price: '$100.00',
    checked: false
  },
  {
    url: img,
    title: 'Windswept Burden',
    price: '$100.00',
    checked: false
  },
  {
    url: img,
    title: 'Windswept Burden',
    price: '$100.00',
    checked: false
  },
  {
    url: img,
    title: 'Windswept Burden',
    price: '$100.00',
    checked: false
  },
  {
    url: img,
    title: 'Windswept Burden',
    price: '$100.00',
    checked: false
  }
])
const dataListRef = ref<HTMLDivElement | null>(null)
const gridColumnCount = shallowRef(1)
let gridResizeObserver: ResizeObserver | null = null

watch(
  () => filters,
  (val) => {
    console.log(val)
  },
  { deep: true }
)

const selectedCount = computed(() => {
  return dataList.value.filter((el) => el.checked === true).length
})
const allCategoriesSelected = computed(() => {
  return (
    filters.categories.length === categoryValues.value.length &&
    categoryValues.value.every((value) => filters.categories.includes(value))
  )
})

const isCategoryActive = (value: string) => {
  if (value === 'all') {
    return allCategoriesSelected.value
  }

  return filters.categories.includes(value)
}

const toggleCategory = (value: string) => {
  if (value === 'all') {
    filters.categories = allCategoriesSelected.value ? [] : [...categoryValues.value]
    return
  }

  if (filters.categories.includes(value)) {
    filters.categories = filters.categories.filter((item) => item !== value)
    return
  }

  filters.categories = [...filters.categories, value]
}

const setGender = (value: string) => {
  filters.gender = value
}

const clearFilters = () => {
  filters.categories = [...categoryValues.value]
  filters.gender = 'all'
}

const handleSelectItem = (item) => {
  console.log('111', item)
  item.checked = !item.checked
}

const handleSelectAll = (flag) => {
  dataList.value.forEach((item) => {
    item.checked = flag
  })
}

const handleDownloadSelected = () => {
  const items = dataList.value.filter((item) => item.checked)
  console.log(items)
}

const updateGridColumnCount = () => {
  if (!dataListRef.value) {
    gridColumnCount.value = 1
    return
  }

  const templateColumns = window.getComputedStyle(dataListRef.value).gridTemplateColumns
  const columnCount =
    templateColumns && templateColumns !== 'none'
      ? templateColumns.split(' ').filter(Boolean).length
      : 1

  gridColumnCount.value = Math.max(columnCount, 1)
}

const isLastColumn = (index: number) => {
  return (index + 1) % gridColumnCount.value === 0
}

const goToDigitalItems = () => {
  router.push('/digitalItem')
}

onMounted(() => {
  nextTick(() => {
    updateGridColumnCount()

    if (!dataListRef.value || typeof ResizeObserver === 'undefined') {
      return
    }

    gridResizeObserver = new ResizeObserver(() => {
      updateGridColumnCount()
    })
    gridResizeObserver.observe(dataListRef.value)
  })
})

onUnmounted(() => {
  gridResizeObserver?.disconnect()
})
</script>
<style lang="less" scoped>
.c-svg {
  width: initial;
  height: initial;
}
.wardrobe-assets {
  --wardrobe-border-color: #d9d4cd;
  --wardrobe-border-dark: #c8c0b4;
  --wardrobe-text-main: #232323;
  --wardrobe-text-secondary: #7a746d;
  --wardrobe-text-muted: #a0978b;
  height: 100%;
  // overflow: hidden;
  padding: 0 9rem 0 10rem;

  .wardrobe-assets__filters {
    width: 26.4rem;
    border-right: 0.1rem solid var(--wardrobe-border-color);
    // background: #fffcf7;
    overflow-y: auto;

    .filters-card {
      padding: 3rem 2.4rem 4rem;

      .filters-card__heading {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 3.2rem;

        .filters-card__title {
          margin: 0;
          font-family: 'KaiseiOpti-Bold';
          font-size: 2.4rem;
          line-height: 1.2;
          color: var(--wardrobe-text-main);
        }

        .filters-card__clear {
          border: 0;
          padding: 0;
          background: transparent;
          font-family: 'KaiseiOpti-Regular';
          font-size: 1.4rem;
          line-height: 1.3;
          color: #9a9185;
          text-decoration: underline;
          cursor: pointer;
        }
      }

      .filter-group {
        & + .filter-group {
          margin-top: 3.4rem;
        }

        .filter-group__title {
          margin: 0 0 1rem;
          font-family: 'KaiseiOpti-Bold';
          font-size: 1.8rem;
          line-height: 1.3;
          color: #5e5851;
        }

        .filter-group__line {
          width: 100%;
          height: 0.1rem;
          background: var(--wardrobe-border-color);
          margin-bottom: 2rem;
        }

        .filter-group__options {
          display: flex;
          flex-direction: column;
          gap: 1.2rem;

          .filter-option {
            display: inline-flex;
            align-items: center;
            gap: 1.2rem;
            width: fit-content;
            padding: 0;
            border: 0;
            background: transparent;
            font-family: 'KaiseiOpti-Regular';
            font-size: 1.5rem;
            line-height: 1.4;
            color: #6e665d;
            cursor: pointer;
            text-align: left;

            > .filter-option__box {
              width: 1.6rem;
              height: 1.6rem;
              border: 0.1rem solid var(--wardrobe-border-dark);
              display: inline-flex;
              align-items: center;
              justify-content: center;
              background: #ffffff;
              flex-shrink: 0;

              .filter-option__tick {
                width: 0.9rem;
                height: 0.5rem;
                border-left: 0.18rem solid #ffffff;
                border-bottom: 0.18rem solid #ffffff;
                transform: rotate(-45deg) translateY(-0.05rem);
                opacity: 0;
              }
            }

            &.is-active {
              color: var(--wardrobe-text-main);

              .filter-option__box {
                border-color: var(--wardrobe-text-main);
                background: var(--wardrobe-text-main);

                .filter-option__tick {
                  opacity: 1;
                }
              }
            }
          }
        }
      }
    }
  }

  .wardrobe-assets__content {
    border-right: 0.05rem solid #585858;
    // &.has-data {
    //   border: none;
    // }

    .assets-toolbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 1.8rem 1.2rem;
      border-bottom: 0.05rem solid #585858;

      .assets-toolbar__selection {
        display: flex;
        align-items: center;
        gap: 1.4rem;
        flex-wrap: wrap;
      }

      .assets-toolbar__selection {
        font-family: 'KaiseiOpti-Regular';
        .select-count {
          column-gap: 1.2rem;
          img {
            width: 2.4rem;
            height: 2.4rem;
          }
          .assets-toolbar__count {
            position: relative;
            font-size: 1.4rem;
            line-height: 1.2;
            color: #57524b;
          }
        }

        .assets-toolbar__link {
          border: 0;
          padding: 0;
          cursor: pointer;
          font-size: 1.4rem;
          color: #a0978b;
          text-decoration: underline;
        }
      }

      .assets-toolbar__actions {
        display: flex;
        align-items: center;

        .assets-toolbar__download {
          height: 4.4rem;
          padding: 0 3rem;
          border: 0.1rem solid #232323;
          background: #232323;
          font-family: 'KaiseiOpti-Regular';
          font-size: 1.3rem;
          color: #fff;
          cursor: pointer;
          column-gap: 1.2rem;
          &.disabled {
            background-color: #979797;
            border-color: #979797;
          }
        }
      }
    }

    .data-list-container {
      overflow-y: auto;
      padding-bottom: 8rem;
      &::-webkit-scrollbar {
        display: none;
      }
      .data-list {
        width: 100%;
        flex: 1;
        display: grid;
        align-content: start;
        grid-template-columns: repeat(auto-fit, minmax(min(100%, 28rem), 1fr));
        border-top: 0.05rem solid #585858;
        border-left: 0.05rem solid #585858;

        .item {
          width: 100%;
          min-width: 0;
          padding: 1.2rem;
          background: #ffffff;
          position: relative;
          box-sizing: border-box;
          border-bottom: 0.05rem solid #585858;

          &:not(.is-last-column) {
            border-right: 0.05rem solid #585858;
          }

          .checkbox {
            position: absolute;
            top: 1.2rem;
            left: 1.2rem;
            width: 2.4rem;
            height: 2.4rem;
            border: 0.15rem solid #585858;
            cursor: pointer;
          }

          :deep(.commodity-item) {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>
