const PagesColumn = {
	name: 'PagesColumn',
	components: {
		LinksyButton,
		LinksyDropdown,
		LinksyModal
	},
	props: {
		item: Object,
		search: String,
		expand: Boolean,
		actions: Array,
		selectedAction: String,
		isApplying: Boolean,
		isGettingOffset: Boolean,
		isApplyDisabled: Boolean,
		isItemSelected: Function
	},
	directives: {
		'linksy-dom-text': LinksyDOMText,
		'linksy-tooltip': LinksyTooltip,
	},
	data() {
		return {
			active: false,
			isViewingOthers: false,
			selectedResult: {},
			opened: false,
			isLoading: false,
			isSaving: false,
			isEditing: false,
			itemDetails: {},
			selectedItemDetails: {},
			fullItemDetails: {}
		}
	},
	computed: {
		allLinksSelectedInColumn() {
			return this.item.columns_results.map(col => col.results.every(res => this.isItemSelected(this.item, col, res, false)));
		},
		hasSelectedItems() {
			return this.item.columns_results.some(col => col.results.some(res => this.isItemSelected(this.item, col, res, false)));
		}
	},
	methods: {
		truncateText(value) {
			const searchTerm = this.search && this.search.trim();
			
			if (value.length > 150 && searchTerm) {
			  const searchLower = searchTerm.toLowerCase();
			  const valueLower = value.toLowerCase();
			  
			  if (valueLower.includes(searchLower)) {
				const searchStartIndex = valueLower.indexOf(searchLower);
				const searchEndIndex = searchStartIndex + searchTerm.length;
				const maxLength = 150;
				let truncatedText = '';
		
				const beforeTextLimit = Math.min(20, searchStartIndex);
				const afterTextLimit = Math.min(100, value.length - searchEndIndex);
				
				const totalLength = beforeTextLimit + searchTerm.length + afterTextLimit;
				
				if (totalLength <= maxLength) {
				  truncatedText = value.substring(searchStartIndex - beforeTextLimit, searchEndIndex + afterTextLimit);
				} else {
				  const remainingSpace = maxLength - searchTerm.length;
				  const availableBeforeText = Math.min(remainingSpace / 2, searchStartIndex);
				  const availableAfterText = remainingSpace - availableBeforeText;
				  
				  truncatedText = value.substring(searchStartIndex - availableBeforeText, searchEndIndex + availableAfterText);
				}
		
				if (searchStartIndex > beforeTextLimit) {
				  truncatedText = '...' + truncatedText;
				}
		
				return truncatedText + '...';
			  } else {
				return value.substring(0, 150) + '...';
			  }
			}
		
			return value.length > 150 ? value.substring(0, 150) + '...' : value;
		},
		async getItemDetails() {
			this.isLoading = true

			try {
				const params = urlSearchParams({
					action: 'linksy_search_and_replace_item_details',
					nonce: LINKSY_SECURE_TOKEN,
					option: 'get',
					item: JSON.stringify(this.selectedResult),
					table_name: this.item.table_name,
				})

				const {
					data: { data },
				} = await axios.post(ajaxurl, params)

				this.selectedItemDetails = data.selected_details
				this.fullItemDetails = data.other_details
			} catch (error) {
				this.$toast.error(error.response?.data?.data || error.message)
			} finally {
				this.isLoading = false
			}
		},
		async setItemDetails() {
			this.isSaving = true

			try {
				const firstKey = Object.keys(this.selectedItemDetails)[0];
				this.selectedResult.result.value = this.selectedItemDetails[firstKey];
				const updatedItem = JSON.stringify({ ...this.selectedResult });
				
				const params = urlSearchParams({
					action: 'linksy_search_and_replace_item_details',
					nonce: LINKSY_SECURE_TOKEN,
					option: 'set',
					item: updatedItem,
					table_name: this.item.table_name,
				})

				const {
					data: { data },
				} = await axios.post(ajaxurl, params)

				this.$toast.success('Column has been updated successfully!')
				this.opened = false
				this.isViewingOthers = false
				this.isEditing = false
			} catch (error) {
				this.$toast.error(error.response?.data?.data || error.message)
			} finally {
				this.isSaving = false
			}
		},
		handleSelectAll(colIndex) {
			const column = this.item.columns_results[colIndex];
			const allSelected = this.allLinksSelectedInColumn[colIndex];

			column.selectAll = !allSelected;

			this.$emit("onSelectAll", this.item, column);
		},
		onSelect(col, result, isTableBased) {
			this.$emit("onSelectResult", this.item, col, result, isTableBased);
		},
		toggleActive() {
			this.active = !this.active
		},
		totalResults(columnsResults) {
			return columnsResults.reduce((sum, col) => sum + (col.results ? col.results.length : 0), 0);
		},
		selectedCountPerColumn(col) {
			const total = col.results.length;
			const selected = col.results.filter(res => this.isItemSelected(this.item, col, res, false)).length;
			return selected
		},
		setSelectedResult(resIndex, colIndex) {
			this.selectedResult = {
				id: resIndex,
				column: this.item.columns_results[colIndex].column_name,
				result: this.item.columns_results[colIndex].results[resIndex]
			}

			this.opened = true
			window.scrollTo({top: 0, behavior: 'smooth'});
			this.getItemDetails()
		},
		isArray(value) {
			return Array.isArray(value);
		},
		closeActiveItem() {
			this.$emit('on-close-item')
		},

		selectAction(index) {
			this.$emit('on-select-action', index)
		},
		handleApplyAction() {
			this.$emit('on-apply')
		},
		handleCancel() {
			this.$emit('on-cancel')
		},
		handleShowMore(col) {
			this.$emit('on-show-more', {table_name: this.item.table_name, column_name: col.column_name, offset: col.results.length})
		}
    },
	watch: {
		expand: function (val) {
			if (!val && this.active) {
				this.active = false
			}
		},
		active: {
			handler: function (val) {
				this.$emit('onToggle', val)
			},
		},
	},
	template: `
    <div class="columns d-flex flex-column gap-3" style="max-height: 460px; overflow-y: auto; overflow-x: hidden;">
        <div @click="toggleActive" v-if="!active" class="position-relative column collasped text-center p-2 m-0 fs-6 cursor-pointer">
            <span>Columns: <span class="item-count">{{item.columns_results.map(e => e.column_name).length}}</span></span>
            &nbsp;
            <span>Results: <span class="item-count">{{totalResults(item.columns_results)}}</span></span>

			<span class="toggle-caret position-absolute"><i class="fa" :class="'fa-angle-' + (active ? 'up' : 'down')"></i></span>
        </div>
        <div v-if="active" v-for="(col, colIndex) in item.columns_results" class="column expanded me-2">
            <div class="column-name d-flex justify-content-between align-items-center position-relative cursor-pointer" @click="closeActiveItem">
                <h4 class="m-0 fw-medium">{{col.column_name}}</h4>
				<span v-if="colIndex === 0"><i class="fa" :class="'fa-angle-' + (active ? 'up' : 'down')"></i></span>
            </div>
			<div class="db-column-content">
				<div v-for="(res, resIndex) in col.results">
					<div class="link-anchor-container d-flex flex-column gap-3">
						<h5 class="d-flex align-items-start gap-2 m-0">
							<span class="linksy-checkbox mt-1" @click="onSelect(col, res, false)" :class="{'checked': isItemSelected(item, col, res, false)}" />
							<div class="column-item-container position-relative w-100">
								<span class="fw-medium text-overflow-wrap">
									{{!isArray(search) ? truncateText(res.value) : res.value}}
								</span>
								<ul class="item-links align-items-center gap-2 m-0">
									<li class="m-0 cursor-pointer" @click="setSelectedResult(resIndex, colIndex)">View</li>
								</ul>
							</div>
						</h5>
					</div>
					<hr class="m-0" v-if="resIndex != col.results.length - 1" />
				</div>

				<div v-if="col.result_length > col.results.length" class="fs-14px cursor-pointer p-3 pt-0 text-primary">
					<div class="d-flex justify-content-between align-items-center gap-2">
						<span>
							<i v-if="isGettingOffset" class="fa fa-spinner fa-spin"></i>
							<span v-else @click="handleShowMore(col)">Load More...</span>
						</span>
						<div>
							Showing {{ col.current_results_length }} of {{ col.result_length }}
						</div>
					</div>
				</div>
			</div>

			<div class="sticky-buttons-container position-sticky bottom-0 z-1">
				<hr class="m-0" />
				<div class="d-flex justify-content-between align-items-center pe-3">
					<div class="action-buttons z-1 d-flex gap-2">
						<linksy-button @click="handleSelectAll(colIndex)" variant="white" class="d-flex align-items-center gap-2">
							<span class="linksy-checkbox" :class="{'checked': allLinksSelectedInColumn[colIndex]}"></span>
							Select all
						</linksy-button>

						<div class="action-dropdown">
							<linksy-dropdown
								is-manual
								is-async
								:initial-value="actions.find(e => e.value == selectedAction)?.label"
								:options="actions"
								class="items-column-actions d-flex align-items-center bg-white text-dark border border-1 rounded-3"
							>
								<template #title>
									<span class="text-nowrap">Bulk action</span>
								</template>
								<template #item="{ item, index, selected }">
									<div class="d-flex w-100 gap-1 align-items-center" @click="selectAction(index)">
										<div class="linksy-checkbox" :class="{'checked': selectedAction === item.value}" />
										<label class="cursor-pointer">{{ item.label }}</label>
										<span class="ms-auto text-wrap" v-linksy-tooltip="{ message: actions[index]?.message, flow: 'right' }"></span>
									</div>
								</template>
								<template #footer="props">
									<div class="actions-button d-flex gap-2">
										<linksy-button class="flex-grow-1" :disabled="isApplyDisabled" :loading="isApplying" @click="handleApplyAction">Apply</linksy-button>
										<linksy-button variant="secondary" class=" flex-grow-1" @click="handleCancel">Cancel</linksy-button>
									</div>
								</template>
							</linksy-dropdown>
						</div>
					</div>

					<div v-if="selectedCountPerColumn(col) > 0" class="selected-count text-primary fs-14px">
						Selected {{ selectedCountPerColumn(col) }} of {{ col.current_results_length }}
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="selected-result">
		<linksy-modal
			v-if="opened"
			:opened="opened"
			title="Details"
			@on-cancel="() => {opened = false; isViewingOthers = false; isEditing = false}"
		>
			<template #body>
				<div class="d-flex flex-column gap-3 bg-white p-3">
					<div v-if="isLoading" class="d-flex flex-column justify-content-center align-items-center py-5">
						<i class="fa fa-spinner fa-spin fs-3"></i>
						<p>Getting details...</p>
					</div>

					<div v-else class="d-flex flex-column gap-3">
						<div>
							<p class="m-0 fw-normal fs-14px">Make changes to this column here. Click save when you're done.</p>
						</div>
						<div class="d-flex flex-column gap-2">
							<div v-for="(value, key) in selectedItemDetails" :key="key" class="d-flex flex-column gap-1">
								<h5 class="fs-14px m-0">{{ key }}</h5>
								<div class="position-relative">
									<div v-if="!isEditing" class="position-absolute top-0 bottom-0 start-0 end-0 d-flex justify-content-end align-items-end z-1">
										<div class="bg-light position-absolute top-0 bottom-0 start-0 end-0 opacity-50"></div>
										<span class="fs-14px fw-normal z-3 cursor-pointer text-decoration-underline text-primary" @click="() => isEditing = !isEditing">edit</span>
									</div>
									<textarea class="fw-normal border border-1 rounded-3 w-100" v-model="selectedItemDetails[key]" :readonly="isSaving">{{ value }}</textarea>
								</div>
								<div v-if="isEditing" class="edit-button d-flex justify-content-end gap-2 mt-2">
									<linksy-button class="shadow-sm" :disabled="isSaving" :loading="isSaving" @click="setItemDetails">
										<i class="fa fa-check"></i>
									</linksy-button>
									<linksy-button variant="secondary" class="shadow-sm" @click="() => isEditing = false">
										<i class="fa fa-times"></i>
									</linksy-button>
								</div>
							</div>

							<span @click="() => isViewingOthers = !isViewingOthers" class="fs-14px cursor-pointer"> <i class="fa" :class="'fa-angle-' + (isViewingOthers ? 'up' : 'down')"></i> {{isViewingOthers ? 'Close' : 'View'}} other details</span>

							<div v-if="isViewingOthers" class="d-flex flex-column gap-2">
								<div v-for="(value, key) in fullItemDetails" :key="key" class="d-flex flex-column gap-1">
									<h5 class="fs-14px m-0">{{ key }}</h5>
									<textarea class="fw-normal border border-1 rounded-3" rows="1" v-model="fullItemDetails[key]" readonly>{{ value }}</textarea>
								</div>
							</div>
						</div>

						<div class="d-none actions-button d-flex gap-2 mt-3">
							<linksy-button :disabled="isSaving" :loading="isSaving" class="w-50" @click="setItemDetails"><i class="fa-solid fa-check me-1"></i> Save</linksy-button>
							<linksy-button variant="secondary" class="w-50" @click="() => opened = false"><i class="fa-solid fa-xmark me-1"></i> Cancel</linksy-button>
						</div>
					</div>
				</div>
			</template>
			<template #footer><div></div></template>
		</linksy-modal>
	</div>
	`,
}