<template>
	<div class="row">
		<div class="col-md-12 panel panel-default">
			<div class="panel-body table-responsive">
				<div class="nominee-filter-chips">
					<button
						type="button"
						class="nominee-chip btn btn-xs"
						:class="position_id == 0 ? 'btn-primary' : 'btn-default'"
						@click="setPosition(0)"
					>
						Semua Jawatan
					</button>
					<button
						v-for="position in data.positions"
						:key="position.id"
						type="button"
						class="nominee-chip btn btn-xs"
						:class="String(position_id) === String(position.id) ? 'btn-primary' : 'btn-default'"
						@click="setPosition(position.id)"
					>
						{{ position.name }}
					</button>
				</div>
				<div class="form-group">
					<router-link :to="{ name: 'Tambah Calon', query: { position_id: position_id } }"
						class="btn btn-success"><i class="fa fa-plus"></i> Tambah Calon</router-link>
				</div>
				<admin-data-table
					:headers="nomineeTableHeaders"
					:items="nominees"
					:loading="nomineeLoading"
					:items-per-page="10"
					:show-pagination="true"
					empty-text="Tiada calon"
					:exportable="true"
					export-file-name="calon"
				>
					<template v-slot:item-photo="{ item }">
						<img
							:alt="item.name"
							:src="createBase64ImageUrl(item.photo)"
							class="thumbnail"
							style="height: 60px; width: 60px;"
						>
					</template>

					<template v-slot:item-education="{ item }">
						<ol style="margin: 0; padding-left: 18px;">
							<li v-for="(x, idx) in (item.education || [])" :key="idx">{{ x }}</li>
						</ol>
					</template>

					<template v-slot:item-experience="{ item }">
						<ol style="margin: 0; padding-left: 18px;">
							<li v-for="(x, idx) in (item.experience || [])" :key="idx">{{ x }}</li>
						</ol>
					</template>

					<template v-slot:item-actions="{ item }">
						<router-link :to="{ name: 'Edit Nominee', params: { id: item.id } }" class="btn btn-primary">
							<i class="fa fa-edit"></i>Kemaskini
						</router-link>
						<button type="button" class="btn btn-danger" @click="openDeleteModal(item)">
							<i class="fa fa-trash"></i>Padam
						</button>
					</template>
				</admin-data-table>
			</div>
		</div>

		<modal id="delete-nominee-modal">
			<modal-header>Padam Calon</modal-header>
			<modal-body>
				<h3>Are you sure to delete this nominee?</h3>
			</modal-body>
			<modal-footer>
				<button class="btn btn-danger" @click="deleteNominee()">Padam</button>
				<button class="btn btn-default" @click="util.hideModal('#delete-nominee-modal')">
					Kembali
				</button>
			</modal-footer>
		</modal>
	</div>

</template>

<script>
export default {


	data: function () {
		return {
			id: 0,
			nomineeLoading: false,
			nomineeTableHeaders: [
				{ title: '', key: 'photo', sortable: false },
				{ title: 'Nama', key: 'name', sortable: true },
				{ title: 'No. Anggota', key: 'no_anggota', sortable: true },
				{ title: 'Unit', key: 'unit', sortable: true },
				{ title: 'Jawatan', key: 'position', sortable: true },
				{
					title: 'Taraf Pendidikan',
					key: 'education',
					sortable: false,
					exportValue: function (item) {
						return Array.isArray(item.education) ? item.education.join(' | ') : '';
					}
				},
				{
					title: 'Pengalaman Kerja',
					key: 'experience',
					sortable: false,
					exportValue: function (item) {
						return Array.isArray(item.experience) ? item.experience.join(' | ') : '';
					}
				},
				{ title: 'Tindakan', key: 'actions', sortable: false }
			]
		}
	},

	created: function () {
		this.refreshNominee();
	},

	methods: {
		setPosition: function (id) {
			var q = Object.assign({}, this.$route.query);
			if (!id || String(id) === '0') {
				delete q.position_id;
			} else {
				q.position_id = id;
			}
			this.$router.replace({ query: q });
		},

		openDeleteModal: function (nominee) {
			this.id = nominee.id;
			this.util.showModal('#delete-nominee-modal');
		},

		deleteNominee() {
			const nomineeId = this.id;
			this.util.hideModal('#delete-nominee-modal'); // Hide modal
			this.util.notify('Deleting nominee', 'loading'); // Show loading notification

			axios.delete(config.API + 'nominee/' + nomineeId) // Make DELETE request
				.then(response => {
					$.notifyClose(); // Close notification
					// if (this.util.showResult(response, 'success')) {
					if (response.data && response.data.status === 'success') {
						this.util.notify('Nominee deleted successfully', 'success');


						// Show success notification
						this.refreshNominee(); // Refresh the list of nominees
					} else {
						this.util.notify('Failed to delete nominee', 'error'); // Show error notification

					}
				})
				.catch(error => {
					$.notifyClose(); // Close notification
					this.util.showResult(error, 'error'); // Show error notification
				})
		},

		refreshNominee: function () {
			var vm = this;
			this.nomineeLoading = true;
			this.util.notify('Refreshing Nominees', 'loading');
			axios.get(config.API + 'nominee', {
				params: {
					position_id: this.position_id && String(this.position_id) !== '0' ? this.position_id : undefined
				}
			})
				.then(response => {
					$.notifyClose();
					console.log(response);
					vm.data.nominees = response.data;
				})
				.catch(error => {
					$.notifyClose();
					vm.showResult(error);
				})
				.finally(function () {
					vm.nomineeLoading = false;
				})
		},

		getPosition: function (id) {
			var positions = this.data.positions;
			for (var i in positions)
				if (positions[i].id == id)
					return positions[i]['name'];
		},

		getPartylist: function (id) {
			var partylists = this.data.partylists;
			for (var i in partylists)
				if (partylists[i].id == id)
					return partylists[i]['name'];
			return 'No partylists';
		},

		createBase64ImageUrl: function (base64ImageData) {
			return "data:image/png;base64," + base64ImageData;
		}
	},

	computed: {
		nominees: function () {
			var nominees = [];
			var y = this.data.nominees;
			for (var nominee in this.data.nominees) {
				if (y[nominee].position_id == this.position_id || this.position_id == 0) {
					var x = Object.assign({}, y[nominee]);
					x.position = this.getPosition(y[nominee].position_id);
					x.partylist = this.getPartylist(y[nominee].partylist_id);
					nominees.push(x);
				}
			}
			return nominees;
		},

		position_id: function () {
			return this.$route.query.position_id ? this.$route.query.position_id : 0;
		}
	},

	watch: {
		position_id: function () {
			this.refreshNominee();
		}
	}
}
</script>


<style>
.nominee-filter-chips {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
	margin-bottom: 12px;
}

.nominee-chip {
	border-radius: 999px;
	padding: 6px 10px;
	line-height: 1.1;
}
</style>
