<template>
	<div class="file-explorer">
		<!-- Loading -->
		<NcLoadingIcon v-if="store.loading && !loaded"
			:size="64"
			class="file-explorer__loading" />

		<!-- Error -->
		<NcEmptyContent v-else-if="store.error"
			name="Fehler"
			:description="store.error">
			<template #action>
				<NcButton @click="loadFiles">Erneut versuchen</NcButton>
			</template>
		</NcEmptyContent>

		<!-- Folder does not exist -->
		<div v-else-if="loaded && !store.folderExists" class="file-explorer__warning">
			<div class="file-explorer__warning-icon">
				<AlertCircle :size="48" />
			</div>
			<p class="file-explorer__warning-text">
				Der Ordner <strong>{{ store.folderPath }}</strong> existiert nicht in Nextcloud Files.
			</p>
			<NcButton type="primary" @click="createFolder">
				<template #icon>
					<FolderPlus :size="20" />
				</template>
				Ordner erstellen
			</NcButton>
		</div>

		<!-- Folder exists -->
		<div v-else-if="loaded && store.folderExists">
			<!-- Toolbar -->
			<div class="file-explorer__toolbar">
				<span class="file-explorer__path">
					<Folder :size="16" />
					{{ store.folderPath }}
				</span>
				<NcButton @click="openInFiles">
					<template #icon>
						<OpenInNew :size="20" />
					</template>
					In Nextcloud Files öffnen
				</NcButton>
			</div>

			<!-- Empty folder -->
			<NcEmptyContent v-if="store.files.length === 0"
				name="Leerer Ordner"
				description="Dieser Ordner enthält noch keine Dateien." />

			<!-- File list table -->
			<table v-else class="file-explorer__table">
				<thead>
					<tr>
						<th class="file-explorer__th">Dateiname</th>
						<th class="file-explorer__th file-explorer__th--size">Größe</th>
						<th class="file-explorer__th file-explorer__th--date">Geändert</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="file in store.files"
						:key="file.name"
						class="file-explorer__row"
						@click="openFile(file)">
						<td class="file-explorer__td file-explorer__td--name">
							<Folder v-if="file.type === 'folder'" :size="20" class="file-explorer__icon" />
							<File v-else :size="20" class="file-explorer__icon" />
							{{ file.name }}
						</td>
						<td class="file-explorer__td file-explorer__td--size">
							{{ file.type === 'folder' ? '—' : formatSize(file.size) }}
						</td>
						<td class="file-explorer__td file-explorer__td--date">
							{{ formatTimestamp(file.mtime) }}
						</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { NcButton, NcEmptyContent, NcLoadingIcon } from '@nextcloud/vue'
import { generateUrl } from '@nextcloud/router'
import { useFilesStore } from '../stores/files.js'
import AlertCircle from 'vue-material-design-icons/AlertCircle.vue'
import Folder from 'vue-material-design-icons/Folder.vue'
import FolderPlus from 'vue-material-design-icons/FolderPlus.vue'
import File from 'vue-material-design-icons/File.vue'
import OpenInNew from 'vue-material-design-icons/OpenInNew.vue'
import { formatTimestamp } from '../utils/dateFormat.js'

const props = defineProps({
	memberId: {
		type: Number,
		required: true,
	},
})

const store = useFilesStore()
const loaded = ref(false)

onMounted(async () => {
	await loadFiles()
})

watch(() => props.memberId, async () => {
	loaded.value = false
	await loadFiles()
})

async function loadFiles() {
	await store.fetchMemberFiles(props.memberId)
	loaded.value = true
}

async function createFolder() {
	const success = await store.ensureMemberFolder(props.memberId)
	if (success) {
		loaded.value = true
	}
}

/**
 * Open a file in Nextcloud Files or the Nextcloud viewer.
 */
function openFile(file) {
	// Build the NC Files URL for the file/folder
	const dir = store.folderPath
	if (file.type === 'folder') {
		// Open subfolder in NC Files
		const url = generateUrl('/apps/files/?dir={dir}/{name}', {
			dir,
			name: file.name,
		})
		window.open(url, '_blank')
	} else {
		// Open file in NC Files with the file highlighted
		const url = generateUrl('/apps/files/?dir={dir}&openfile=true&scrollto={name}', {
			dir,
			name: file.name,
		})
		window.open(url, '_blank')
	}
}

/**
 * Open the member folder in Nextcloud Files.
 */
function openInFiles() {
	const url = generateUrl('/apps/files/?dir={dir}', {
		dir: store.folderPath,
	})
	window.open(url, '_blank')
}

/**
 * Format file size in human-readable format.
 *
 * @param {number} bytes - File size in bytes
 * @returns {string} Formatted size (e.g. "1.5 MB")
 */
function formatSize(bytes) {
	if (bytes === 0) return '0 B'
	const units = ['B', 'KB', 'MB', 'GB']
	const i = Math.floor(Math.log(bytes) / Math.log(1024))
	const size = (bytes / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0)
	return size + ' ' + units[i]
}

// formatTimestamp imported from utils/dateFormat.js
</script>

<style scoped>
.file-explorer {
	min-height: 200px;
}

.file-explorer__loading {
	display: flex;
	justify-content: center;
	margin-top: 40px;
}

.file-explorer__warning {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 16px;
	padding: 40px 20px;
	text-align: center;
}

.file-explorer__warning-icon {
	color: var(--color-warning);
}

.file-explorer__warning-text {
	font-size: 1em;
	color: var(--color-text-lighter);
	max-width: 400px;
}

.file-explorer__toolbar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8px 0;
	margin-bottom: 12px;
	border-bottom: 1px solid var(--color-border);
}

.file-explorer__path {
	display: flex;
	align-items: center;
	gap: 6px;
	font-size: 0.9em;
	color: var(--color-text-lighter);
	font-family: monospace;
}

.file-explorer__table {
	width: 100%;
	border-collapse: collapse;
}

.file-explorer__th {
	text-align: left;
	padding: 8px 12px;
	font-weight: 600;
	font-size: 0.85em;
	color: var(--color-text-lighter);
	border-bottom: 2px solid var(--color-border);
}

.file-explorer__th--size {
	width: 100px;
	text-align: right;
}

.file-explorer__th--date {
	width: 160px;
	text-align: right;
}

.file-explorer__row {
	cursor: pointer;
	transition: background-color 0.15s ease;
}

.file-explorer__row:hover {
	background-color: var(--color-background-hover);
}

.file-explorer__td {
	padding: 10px 12px;
	border-bottom: 1px solid var(--color-border);
	font-size: 0.95em;
}

.file-explorer__td--name {
	display: flex;
	align-items: center;
	gap: 8px;
}

.file-explorer__td--size {
	text-align: right;
	color: var(--color-text-lighter);
}

.file-explorer__td--date {
	text-align: right;
	color: var(--color-text-lighter);
}

.file-explorer__icon {
	flex-shrink: 0;
	color: var(--color-primary);
}
</style>
