<template>
	<div class="wardrobe-assets flex">
		<FilterSidebar
			:categories="categories"
			:genders="genders"
			:filters="filters"
			@update:filters="updateFilters"
		/>

		<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 loading="lazy" 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 }"
						v-loading="downloadingSelected"
						@click="handleDownloadSelected(null)"
					>
						<SvgIcon name="downloadBtn" color="#fff" />
						<span>{{ t('Wardrobe.assets.downloadSelected') }}</span>
					</div>
				</div>
			</div>
			<div
				ref="assetsScrollRef"
				v-if="dataList.length"
				class="data-list-container"
				@scroll.passive="handleAssetsScroll"
			>
				<div ref="dataListRef" class="data-list">
					<div
						v-for="(item, index) in dataList"
						:key="item.listingId"
						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.thumbnailUrl"
							:name="item.listingName"
							@download="handleDownloadSelected(item)"
							:showPrice="false"
						></CommodityItem>
					</div>
				</div>
			</div>

			<Empty v-else />
		</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 Empty from './Empty.vue'
	import FilterSidebar from './FilterSidebar.vue'
	import { fetchMyWardrobe, fetchDownloadItemsByGet } from '@/api/user'
	import { useUserInfoStore } from '@/stores'

	import { debounce } from 'lodash-es'

	interface Props {
		sortType?: number
	}

	const props = withDefaults(defineProps<Props>(), {
		sortType: 1
	})

	const buyerId = useUserInfoStore().state.userInfo?.userId

	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 genderValues = computed(() =>
		genders.value.filter((option) => option.value !== 'all').map((option) => option.value)
	)

	const dataList = ref([])
	const rawDataList = ref([]) // Store the original API data
	const dataListRef = ref<HTMLDivElement | null>(null)
	const assetsScrollRef = ref<HTMLDivElement | null>(null)
	const gridColumnCount = shallowRef(1)
	let gridResizeObserver: ResizeObserver | null = null
	const assetsRequestId = ref(0)
	const isLoadingAssets = ref(false)
	const hasMoreAssets = ref(true)

	const filters = reactive({
		categories: ['all'],
		genders: ['all']
	})
	const pageParams = reactive({
		page: 1,
		size: 10
	})
	const handleGetAssets = async () => {
		if (isLoadingAssets.value || !hasMoreAssets.value) return
		isLoadingAssets.value = true
		const requestId = ++assetsRequestId.value

		try {
			const category = filters.categories[0] === 'all' ? [] : filters.categories
			// debugger
			const res = await fetchMyWardrobe({
				buyerId: buyerId,
				categories: category,
				designFor: filters.genders.length > 1 ? 'all' : filters.genders[0] || 'all',
				page: pageParams.page,
				size: pageParams.size
			})

			if (requestId !== assetsRequestId.value) return

			const content = res.content ?? []
			if (pageParams.page === 1) {
				rawDataList.value = content
			} else {
				rawDataList.value = [...rawDataList.value, ...content]
			}

			hasMoreAssets.value = content.length >= pageParams.size
			if (hasMoreAssets.value) {
				pageParams.page += 1
			}

			// Apply sorting after fetching data
			applySorting()
		} finally {
			if (requestId === assetsRequestId.value) {
				isLoadingAssets.value = false
			}
		}
	}

	// Function to apply sorting based on sortType
	const applySorting = () => {
		if (props.sortType === 1) {
			// Date Added - use original API order
			dataList.value = [...rawDataList.value]
		} else if (props.sortType === 2) {
			// Selected First - sort by checked status
			dataList.value = [...rawDataList.value].sort((a, b) => {
				if (a.checked && !b.checked) return -1
				if (!a.checked && b.checked) return 1
				return 0
			})
		}
	}

	// Watch for sortType changes
	watch(
		() => props.sortType,
		() => {
			applySorting()
		}
	)

	watch(
		() => filters,
		debounce(() => {
			pageParams.page = 1
			hasMoreAssets.value = true
			assetsRequestId.value += 1
			handleGetAssets()
		}, 500),
		{ deep: true }
	)

	const selectedCount = computed(() => {
		return dataList.value.filter((el) => el.checked === true).length
	})

	const updateFilters = (value: { categories: string[]; genders: string[] }) => {
		filters.categories = value.categories
		filters.genders = value.genders
	}

	const handleSelectItem = (item) => {
		item.checked = !item.checked
		// Re-apply sorting when selection changes and sortType is "Selected First"
		if (props.sortType === 2) {
			applySorting()
		}
	}

	const handleSelectAll = (flag) => {
		dataList.value.forEach((item) => {
			item.checked = flag
		})
		// Re-apply sorting when selection changes and sortType is "Selected First"
		if (props.sortType === 2) {
			applySorting()
		}
	}

	const downloadingSelected = ref(false)
	const handleDownloadSelected = (assets = null) => {
		const items = assets ? [assets] : dataList.value.filter((item) => item.checked)

		downloadingSelected.value = true
		const ids = items.map((item) => item.listingId)
		fetchDownloadItemsByGet({ ids })
			.then((res) => {
				const disposition = res.headers['content-disposition']
				const fileName =
					disposition?.split('filename=')[1]?.replace(/"/g, '') || 'download.zip'
				const blob = res.data
				const url = window.URL.createObjectURL(blob)

				const link = document.createElement('a')
				link.href = url

				const timestamp = new Date().getTime()
				link.download = fileName || `wardrobe_download_${timestamp}.zip`

				document.body.appendChild(link)
				link.click()

				document.body.removeChild(link)
				window.URL.revokeObjectURL(url)
			})
			.catch((error) => {
				console.error('Download failed:', error)
			})
			.finally(() => {
				downloadingSelected.value = false
			})
	}

	const handleAssetsScroll = () => {
		const el = assetsScrollRef.value
		if (!el || isLoadingAssets.value || !hasMoreAssets.value) return

		const reachBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 120
		if (reachBottom) {
			handleGetAssets()
		}
	}

	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
	}

	watch(
		() => dataList.value.length,
		async (len) => {
			if (!len) return

			await nextTick()

			updateGridColumnCount()

			gridResizeObserver?.disconnect()

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

				gridResizeObserver.observe(dataListRef.value)
			}
		},
		{ immediate: true }
	)
	onMounted(() => {
		handleGetAssets()
	})

	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-fill, minmax(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>
