<template>
	<div class="import-export-page">
		<h2>Import / Export</h2>

		<!-- Tab bar -->
		<div class="import-export-page__tabs">
			<button :class="['import-export-page__tab', { 'import-export-page__tab--active': activeTab === 'export' }]"
				@click="activeTab = 'export'">
				Export
			</button>
			<button :class="['import-export-page__tab', { 'import-export-page__tab--active': activeTab === 'import' }]"
				@click="activeTab = 'import'">
				Import
			</button>
		</div>

		<!-- ═══════ Export Section ═══════ -->
		<div v-if="activeTab === 'export'" class="import-export-page__section">
			<h3>Daten exportieren</h3>

			<div v-if="exportStore.error" class="import-export-page__error">
				{{ exportStore.error }}
				<NcButton type="tertiary" @click="exportStore.clearError()">Schliessen</NcButton>
			</div>

			<!-- ── Full bundle export (Issue #149) ── -->
			<div class="import-export-page__subsection">
				<h4>Vollstaendiger Export</h4>
				<p class="import-export-page__hint">
					Alle Datentabellen als einzelne ZIP-Datei herunterladen (13 CSV-Dateien).
				</p>

				<div class="import-export-page__bundle-controls">
					<NcButton type="primary"
						:disabled="exportStore.bundleLoading"
						@click="exportStore.downloadBundle()">
						<NcLoadingIcon v-if="exportStore.bundleLoading" :size="20" />
						<template v-else>Ohne sensible Daten</template>
					</NcButton>

					<NcButton type="error"
						class="import-export-page__sensitive-btn"
						:disabled="exportStore.bundleLoading"
						@click="exportStore.showSensitiveWarning = true">
						Mit sensiblen Daten (Achtung!)
					</NcButton>
				</div>
			</div>

			<!-- Sensitive data warning dialog -->
			<NcDialog v-if="exportStore.showSensitiveWarning"
				name="Warnung: Sensible Daten"
				size="normal"
				@closing="exportStore.showSensitiveWarning = false">
				<div class="import-export-page__warning-dialog">
					<p class="import-export-page__warning-text">
						<strong>Achtung:</strong> Der Export mit sensiblen Daten enthaelt entschluesselte
						IBAN-Nummern, Kontoinhabernamen und Allergie-Informationen im Klartext.
					</p>
					<p class="import-export-page__warning-text">
						Die heruntergeladene ZIP-Datei ist <strong>nicht passwortgeschuetzt</strong>.
						Bitte behandle die Datei vertraulich und loesche sie nach Verwendung.
					</p>
					<div class="import-export-page__warning-actions">
						<NcButton @click="exportStore.showSensitiveWarning = false">
							Abbrechen
						</NcButton>
						<NcButton type="error"
							:disabled="exportStore.bundleLoading"
							@click="exportStore.downloadBundleSensitive()">
							<NcLoadingIcon v-if="exportStore.bundleLoading" :size="20" />
							<template v-else>Sensiblen Export starten</template>
						</NcButton>
					</div>
				</div>
			</NcDialog>

			<hr class="import-export-page__divider">

			<!-- ── Per-entity CSV export (Issue #148) ── -->
			<div class="import-export-page__subsection">
				<h4>Einzelne Tabelle exportieren</h4>
				<p class="import-export-page__hint">
					Einzelne Datentabelle als CSV-Datei herunterladen (Semikolon-getrennt, UTF-8).
					Verschluesselte Felder (IBAN, Kontoinhaber, Allergien) werden als [verschluesselt] angezeigt.
				</p>

				<div class="import-export-page__export-controls">
					<label class="import-export-page__label">
						Datentyp:
						<select v-model="exportStore.selectedType" class="import-export-page__select">
							<option v-for="t in exportStore.entityTypes" :key="t.key" :value="t.key">
								{{ t.label }}
							</option>
						</select>
					</label>

					<NcButton type="primary"
						:disabled="exportStore.loading || !exportStore.selectedType"
						@click="exportStore.downloadEntity()">
						<NcLoadingIcon v-if="exportStore.loading" :size="20" />
						<template v-else>CSV herunterladen</template>
					</NcButton>
				</div>
			</div>
		</div>

		<!-- ═══════ Import Section ═══════ -->
		<div v-if="activeTab === 'import'" class="import-export-page__section">
			<div class="import-wizard">
				<!-- Step indicator -->
				<div class="import-wizard__steps">
					<span v-for="s in steps"
						:key="s.num"
						:class="['import-wizard__step', {
							'import-wizard__step--active': importStore.step === s.num,
							'import-wizard__step--done': importStore.step > s.num
						}]">
						{{ s.num }}. {{ s.label }}
					</span>
				</div>

				<!-- Error banner -->
				<div v-if="importStore.error" class="import-wizard__error">
					{{ importStore.error }}
					<NcButton type="tertiary" @click="importStore.error = null">Schliessen</NcButton>
				</div>

				<!-- Step 1: Upload -->
				<div v-if="importStore.step === 1" class="import-wizard__content">
					<h3>Datei hochladen</h3>
					<p class="import-wizard__hint">
						Unterstuetzte Formate: CSV (einzelne Tabelle) oder ZIP (vollstaendiges Bundle).
						Der Datentyp wird automatisch anhand der Spaltenkoepfe bzw. Dateinamen erkannt.
					</p>

					<div class="import-wizard__upload-area">
						<label class="import-wizard__option">
							Datentyp (optional, wird automatisch erkannt):
							<select v-model="importStore.entityType" class="import-wizard__select import-wizard__select--wide">
								<option value="">Automatisch erkennen</option>
								<option v-for="t in exportStore.entityTypes" :key="t.key" :value="t.key">
									{{ t.label }}
								</option>
							</select>
						</label>

						<div class="import-wizard__file-row">
							<input ref="fileInput"
								type="file"
								accept=".csv,.txt,.zip"
								class="import-wizard__file-input-hidden"
								@change="onFileSelected">
							<NcButton type="primary" @click="$refs.fileInput.click()">
								Datei auswaehlen
							</NcButton>
							<span v-if="importStore.fileName" class="import-wizard__file-name">
								{{ importStore.fileName }}
							</span>
						</div>

						<div class="import-wizard__options">
							<label class="import-wizard__option">
								Trennzeichen:
								<select v-model="importStore.delimiter" class="import-wizard__select">
									<option value=",">Komma (,)</option>
									<option value=";">Semikolon (;)</option>
									<option value="\t">Tab</option>
								</select>
							</label>
							<label class="import-wizard__option">
								Kodierung:
								<select v-model="importStore.encoding" class="import-wizard__select">
									<option value="UTF-8">UTF-8</option>
									<option value="ISO-8859-1">ISO-8859-1 (Latin-1)</option>
									<option value="Windows-1252">Windows-1252</option>
								</select>
							</label>
						</div>

						<!-- Migration mode toggle (Issue #153) -->
						<label class="import-wizard__checkbox import-wizard__migration-toggle">
							<input v-model="importStore.migrationMode" type="checkbox">
							<strong>Migrationsmodus</strong> -- Daten aus anderer Instanz importieren
							(Zuordnung ueber Namen statt IDs)
						</label>
						<div v-if="importStore.migrationMode" class="import-wizard__migration-hint">
							Im Migrationsmodus werden Datensaetze anhand ihres Inhalts (Name, Datum, etc.)
							statt anhand der Datenbank-IDs zugeordnet. Verwende diesen Modus, wenn du Daten
							aus einer anderen Nextcloud-Instanz importierst.
						</div>
					</div>

					<NcLoadingIcon v-if="importStore.loading" :size="32" />
				</div>

				<!-- Step 2 (Bundle): Analysis summary -->
				<div v-if="importStore.step === 2 && importStore.isBundleImport && importStore.bundleAnalysis"
					class="import-wizard__content">
					<h3>Bundle-Analyse</h3>
					<p class="import-wizard__hint">
						Folgende Datentypen wurden im ZIP-Archiv erkannt.
						Die Import-Reihenfolge wurde automatisch nach Abhaengigkeiten bestimmt.
					</p>

					<table class="import-wizard__mapping-table">
						<thead>
							<tr>
								<th>Reihenfolge</th>
								<th>Datentyp</th>
								<th>Dateiname</th>
								<th>Zeilen</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(e, idx) in importStore.bundleAnalysis.entities" :key="e.type">
								<td>{{ idx + 1 }}</td>
								<td><strong>{{ e.label }}</strong></td>
								<td class="import-wizard__col-preview">{{ e.filename }}</td>
								<td>{{ e.rowCount }}</td>
							</tr>
						</tbody>
					</table>

					<div v-if="importStore.bundleAnalysis.unknown.length > 0" class="import-wizard__section">
						<h4>Nicht erkannte Dateien</h4>
						<div v-for="f in importStore.bundleAnalysis.unknown" :key="f"
							class="import-wizard__warning-row">
							{{ f }} -- Datentyp nicht erkannt
						</div>
					</div>

					<div class="import-wizard__nav">
						<NcButton @click="importStore.reset()">Zurueck</NcButton>
						<NcButton type="primary"
							:disabled="importStore.loading || importStore.bundleAnalysis.entities.length === 0"
							@click="importStore.runBundlePreview()">
							<NcLoadingIcon v-if="importStore.loading" :size="20" />
							Dry-Run starten
						</NcButton>
					</div>
				</div>

				<!-- Step 2 (CSV): Column mapping -->
				<div v-if="importStore.step === 2 && !importStore.isBundleImport" class="import-wizard__content">
					<h3>Spaltenzuordnung</h3>

					<!-- Auto-detection info -->
					<div v-if="importStore.detection" class="import-wizard__detection">
						<span v-if="importStore.detection.type">
							Erkannter Datentyp: <strong>{{ entityTypeLabel }}</strong>
							({{ Math.round(importStore.detection.confidence * 100) }}% Uebereinstimmung)
						</span>
						<span v-else class="import-wizard__detection--unknown">
							Datentyp konnte nicht automatisch erkannt werden. Bitte manuell auswaehlen.
						</span>
					</div>

					<label class="import-wizard__option import-wizard__entity-select">
						Datentyp:
						<select :value="importStore.entityType"
							class="import-wizard__select import-wizard__select--wide"
							@change="onEntityTypeChange($event.target.value)">
							<option v-for="t in exportStore.entityTypes" :key="t.key" :value="t.key">
								{{ t.label }}
							</option>
						</select>
					</label>

					<p class="import-wizard__hint">
						Ordne die Spalten aus der CSV-Datei den Feldern zu.
						Pflichtfelder sind mit * markiert.
					</p>

					<table class="import-wizard__mapping-table">
						<thead>
							<tr>
								<th>CSV-Spalte</th>
								<th>Beispielwert</th>
								<th>Zuordnen zu</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(col, idx) in importStore.columns" :key="idx">
								<td class="import-wizard__col-name">{{ col }}</td>
								<td class="import-wizard__col-preview">
									{{ importStore.previewRows[0]?.[idx] || '\u2014' }}
								</td>
								<td>
									<select v-model="importStore.mapping[idx]" class="import-wizard__select">
										<option value="">\u2014 Nicht importieren \u2014</option>
										<option v-for="f in importStore.targetFields"
											:key="f.key"
											:value="f.key">
											{{ f.label }}{{ f.required ? ' *' : '' }}
										</option>
									</select>
								</td>
							</tr>
						</tbody>
					</table>

					<div class="import-wizard__nav">
						<NcButton @click="importStore.step = 1">Zurueck</NcButton>
						<NcButton type="primary"
							:disabled="!importStore.allRequiredMapped || !importStore.entityType"
							@click="goToPreview">
							Vorschau
						</NcButton>
					</div>
				</div>

				<!-- Step 3: Preview table -->
				<div v-if="importStore.step === 3" class="import-wizard__content">
					<h3>Daten-Vorschau</h3>
					<p class="import-wizard__hint">
						Vorschau der zugeordneten Daten (erste {{ Math.min(importStore.previewRows.length, 20) }}
						von {{ importStore.totalRows }} Zeilen).
						Datentyp: <strong>{{ entityTypeLabel }}</strong>
					</p>

					<div class="import-wizard__preview-scroll">
						<table class="import-wizard__preview-table">
							<thead>
								<tr>
									<th v-for="f in mappedFields" :key="f.key">{{ f.label }}</th>
								</tr>
							</thead>
							<tbody>
								<tr v-for="(row, idx) in previewMapped" :key="idx">
									<td v-for="f in mappedFields" :key="f.key">
										{{ row[f.key] || '\u2014' }}
									</td>
								</tr>
							</tbody>
						</table>
					</div>

					<div class="import-wizard__nav">
						<NcButton @click="importStore.step = 2">Zurueck</NcButton>
						<NcButton type="primary"
							:disabled="importStore.loading"
							@click="importStore.runPreview()">
							<NcLoadingIcon v-if="importStore.loading" :size="20" />
							Dry-Run starten
						</NcButton>
					</div>
				</div>

				<!-- Step 4 (Bundle): Dry-run results -->
				<div v-if="importStore.step === 4 && importStore.isBundleImport && importStore.bundlePreviewResult"
					class="import-wizard__content">
					<h3>Bundle Dry-Run Ergebnis</h3>

					<div v-for="res in importStore.bundlePreviewResult.results" :key="res.type"
						class="import-wizard__bundle-entity">
						<h4>{{ res.label }}</h4>
						<div class="import-wizard__summary">
							<div class="import-wizard__summary-item import-wizard__summary-item--success">
								<strong>{{ res.summary.toCreate }}</strong> zu erstellen
							</div>
							<div class="import-wizard__summary-item import-wizard__summary-item--warning">
								<strong>{{ res.summary.duplicates }}</strong> Duplikate
							</div>
							<div class="import-wizard__summary-item import-wizard__summary-item--error">
								<strong>{{ res.summary.errors }}</strong> Fehler
							</div>
						</div>
						<div v-if="res.errors && res.errors.length > 0" class="import-wizard__section">
							<h4>Fehler -- Daten korrigieren</h4>
							<p class="import-wizard__hint">
								Klicke auf eine Zeile, um die Daten zu bearbeiten und fehlende Felder zu ergaenzen.
							</p>

							<div v-for="(err, eIdx) in res.errors.slice(0, 10)" :key="'be-' + eIdx"
								class="import-wizard__error-row import-wizard__error-row--fixable">
								<div class="import-wizard__error-header"
									@click="toggleBundleErrorExpand(res.type, err._rowIndex)">
									<span class="import-wizard__error-toggle">
										{{ isBundleErrorExpanded(res.type, err._rowIndex) ? '\u25BC' : '\u25B6' }}
									</span>
									<strong>Zeile {{ err._rowIndex }}:</strong>
									<span class="import-wizard__error-msgs">
										{{ err._errors.join('; ') }}
									</span>
									<span v-if="hasBundleCorrections(res.type, err._rowIndex)" class="import-wizard__error-badge">
										bearbeitet
									</span>
								</div>

								<div v-if="isBundleErrorExpanded(res.type, err._rowIndex)" class="import-wizard__error-fields">
									<div v-for="f in getBundleEditableFields(res)" :key="f.key"
										class="import-wizard__error-field">
										<label :class="{ 'import-wizard__error-field--required': f.required }">
											{{ f.label }}{{ f.required ? ' *' : '' }}
										</label>
										<input
											:value="getBundleCorrectedValue(res.type, err._rowIndex, f.key, err[f.key])"
											:placeholder="f.type === 'date' ? 'YYYY-MM-DD' : ''"
											class="import-wizard__error-input"
											:class="{ 'import-wizard__error-input--missing': f.required && !getBundleCorrectedValue(res.type, err._rowIndex, f.key, err[f.key]) }"
											@input="onBundleCorrectionInput(res.type, err._rowIndex, f.key, $event.target.value)">
									</div>
								</div>
							</div>
						</div>
					</div>

					<div v-if="hasBundleCorrectedRows" class="import-wizard__revalidate">
						<NcButton
							:disabled="importStore.loading"
							@click="importStore.runBundlePreview()">
							<NcLoadingIcon v-if="importStore.loading" :size="20" />
							<template v-else>Erneut pruefen</template>
						</NcButton>
					</div>

					<div class="import-wizard__nav">
						<NcButton @click="importStore.step = 2">Zurueck</NcButton>
						<NcButton type="primary"
							:disabled="importStore.loading || bundleTotalToCreate === 0"
							@click="importStore.executeBundleImport()">
							<NcLoadingIcon v-if="importStore.loading" :size="20" />
							Bundle importieren ({{ bundleTotalToCreate }} Eintraege)
						</NcButton>
					</div>
				</div>

				<!-- Step 4 (CSV): Dry-run results -->
				<div v-if="importStore.step === 4 && !importStore.isBundleImport && importStore.previewResult" class="import-wizard__content">
					<h3>Dry-Run Ergebnis ({{ entityTypeLabel }})</h3>

					<div class="import-wizard__summary">
						<div class="import-wizard__summary-item import-wizard__summary-item--success">
							<strong>{{ importStore.previewResult.summary.toCreate }}</strong> zu erstellen
						</div>
						<div class="import-wizard__summary-item import-wizard__summary-item--warning">
							<strong>{{ importStore.previewResult.summary.duplicates }}</strong> Duplikate
						</div>
						<div class="import-wizard__summary-item import-wizard__summary-item--error">
							<strong>{{ importStore.previewResult.summary.errors }}</strong> Fehler
						</div>
					</div>

					<!-- Migration mode indicator -->
					<div v-if="importStore.migrationMode" class="import-wizard__migration-active">
						Migrationsmodus aktiv -- Zuordnung ueber Inhalte
					</div>

					<!-- Ambiguous matches (migration mode) -->
					<div v-if="importStore.ambiguousWarnings.length > 0" class="import-wizard__section">
						<h4>Mehrdeutige Zuordnungen</h4>
						<p class="import-wizard__hint">
							Die folgenden Datensaetze konnten nicht eindeutig zugeordnet werden.
							Bitte pruefe die Zuordnung manuell.
						</p>
						<div v-for="(a, idx) in importStore.ambiguousWarnings" :key="'amb-' + idx"
							class="import-wizard__ambiguous-row">
							Zeile {{ a.row }}: {{ a.message }}
						</div>
					</div>

					<!-- FK Warnings -->
					<div v-if="importStore.fkWarnings.length > 0" class="import-wizard__section">
						<h4>Fremdschluessel-Warnungen</h4>
						<div v-for="(w, idx) in importStore.fkWarnings" :key="'fk-' + idx"
							class="import-wizard__warning-row">
							Zeile {{ w.row }}: {{ w.message }}
						</div>
					</div>

					<!-- Errors with inline editing -->
					<div v-if="importStore.previewResult.errors.length > 0" class="import-wizard__section">
						<h4>Fehler -- Daten korrigieren</h4>
						<p class="import-wizard__hint">
							Klicke auf eine Zeile, um die Daten zu bearbeiten und fehlende Felder zu ergaenzen.
						</p>

						<div v-for="(err, idx) in importStore.previewResult.errors" :key="'e-' + idx"
							class="import-wizard__error-row import-wizard__error-row--fixable">
							<div class="import-wizard__error-header"
								@click="toggleErrorExpand(err._rowIndex)">
								<span class="import-wizard__error-toggle">
									{{ expandedErrors[err._rowIndex] ? '\u25BC' : '\u25B6' }}
								</span>
								<strong>Zeile {{ err._rowIndex }}:</strong>
								<span class="import-wizard__error-msgs">
									{{ err._errors.join('; ') }}
								</span>
								<span v-if="hasCorrections(err._rowIndex)" class="import-wizard__error-badge">
									bearbeitet
								</span>
							</div>

							<div v-if="expandedErrors[err._rowIndex]" class="import-wizard__error-fields">
								<div v-for="f in editableFields" :key="f.key"
									class="import-wizard__error-field">
									<label :class="{ 'import-wizard__error-field--required': f.required }">
										{{ f.label }}{{ f.required ? ' *' : '' }}
									</label>
									<input
										:value="getCorrectedValue(err._rowIndex, f.key, err[f.key])"
										:placeholder="f.type === 'date' ? 'YYYY-MM-DD' : ''"
										class="import-wizard__error-input"
										:class="{ 'import-wizard__error-input--missing': f.required && !getCorrectedValue(err._rowIndex, f.key, err[f.key]) }"
										@input="onCorrectionInput(err._rowIndex, f.key, $event.target.value)">
								</div>
							</div>
						</div>

						<div class="import-wizard__revalidate">
							<NcButton
								:disabled="importStore.loading || !hasCorrectedRows"
								@click="importStore.runPreview()">
								<NcLoadingIcon v-if="importStore.loading" :size="20" />
								<template v-else>Erneut pruefen</template>
							</NcButton>
						</div>
					</div>

					<!-- Duplicates with conflict resolution -->
					<div v-if="importStore.previewResult.duplicates.length > 0" class="import-wizard__section">
						<h4>Duplikate -- Konflikte loesen</h4>
						<p class="import-wizard__hint">
							Fuer jedes Duplikat kannst du pro Feld entscheiden, ob der bestehende oder
							der importierte Wert verwendet werden soll.
							Leere Felder im Bestand werden automatisch mit importierten Werten vorbelegt.
						</p>
						<ConflictResolver
							:conflicts="importStore.previewResult.duplicates"
							:field-defs="importStore.targetFields"
							@update:resolutions="onConflictResolutions" />
					</div>

					<div class="import-wizard__nav">
						<NcButton @click="importStore.step = 2">Zurueck zur Zuordnung</NcButton>
						<NcButton v-if="importStore.previewResult.duplicates.length > 0"
							:disabled="importStore.loading || hasUnresolvedConflicts"
							@click="onExecuteWithMerge">
							<NcLoadingIcon v-if="importStore.loading" :size="20" />
							Zusammenfuehren und importieren
						</NcButton>
						<NcButton type="primary"
							:disabled="importStore.loading || importStore.previewResult.summary.toCreate === 0"
							@click="importStore.executeImport()">
							<NcLoadingIcon v-if="importStore.loading" :size="20" />
							Import ausfuehren ({{ importStore.previewResult.summary.toCreate }} neue Eintraege)
						</NcButton>
					</div>
				</div>

				<!-- Step 5 (Bundle): Final results -->
				<div v-if="importStore.step === 5 && importStore.isBundleImport && importStore.bundleExecuteResult"
					class="import-wizard__content">
					<h3>Bundle-Import abgeschlossen</h3>

					<table class="import-wizard__mapping-table">
						<thead>
							<tr>
								<th>Datentyp</th>
								<th>Erstellt</th>
								<th>Uebersprungen</th>
								<th>Fehler</th>
								<th>Status</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="res in importStore.bundleExecuteResult.results" :key="res.type">
								<td><strong>{{ res.label }}</strong></td>
								<td class="import-wizard__col-preview">{{ res.created }}</td>
								<td class="import-wizard__col-preview">{{ res.skipped }}</td>
								<td class="import-wizard__col-preview">{{ res.errors }}</td>
								<td>
									<span v-if="res.status === 'success'" class="import-wizard__status-ok">Erfolgreich</span>
									<span v-else class="import-wizard__status-err">{{ res.error || 'Fehler' }}</span>
								</td>
							</tr>
						</tbody>
					</table>

					<div class="import-wizard__nav">
						<NcButton @click="importStore.reset()">
							Neuer Import
						</NcButton>
					</div>
				</div>

				<!-- Step 5 (CSV): Final results -->
				<div v-if="importStore.step === 5 && !importStore.isBundleImport && importStore.executeResult" class="import-wizard__content">
					<h3>Import abgeschlossen ({{ entityTypeLabel }})</h3>

					<div class="import-wizard__summary">
						<div class="import-wizard__summary-item import-wizard__summary-item--success">
							<strong>{{ importStore.executeResult.created }}</strong> erstellt
						</div>
						<div v-if="importStore.mergeResult" class="import-wizard__summary-item import-wizard__summary-item--merge">
							<strong>{{ importStore.mergeResult.updated }}</strong> aktualisiert
						</div>
						<div class="import-wizard__summary-item import-wizard__summary-item--warning">
							<strong>{{ importStore.executeResult.skipped }}</strong> uebersprungen
						</div>
						<div class="import-wizard__summary-item import-wizard__summary-item--error">
							<strong>{{ importStore.executeResult.errors + (importStore.mergeResult?.errors || 0) }}</strong> Fehler
						</div>
					</div>

					<div class="import-wizard__nav">
						<NcButton @click="importStore.reset()">
							Neuer Import
						</NcButton>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { computed, ref, reactive, onMounted } from 'vue'
import { NcButton, NcDialog, NcLoadingIcon } from '@nextcloud/vue'
import { useImportStore } from '../stores/import.js'
import { useExportStore } from '../stores/export.js'
import ConflictResolver from '../components/ConflictResolver.vue'

const importStore = useImportStore()
const exportStore = useExportStore()

const activeTab = ref('export')

const steps = [
	{ num: 1, label: 'Hochladen' },
	{ num: 2, label: 'Zuordnung' },
	{ num: 3, label: 'Vorschau' },
	{ num: 4, label: 'Dry-Run' },
	{ num: 5, label: 'Ergebnis' },
]

onMounted(() => {
	exportStore.fetchEntityTypes()
})

/**
 * Human-readable label for the selected entity type.
 */
const entityTypeLabel = computed(() => {
	const found = exportStore.entityTypes.find(t => t.key === importStore.entityType)
	return found?.label || importStore.entityType || 'Unbekannt'
})

/**
 * The target fields that have a mapping assigned.
 */
const mappedFields = computed(() => {
	const mappedKeys = Object.values(importStore.mapping).filter(v => v !== '')
	return importStore.targetFields.filter(f => mappedKeys.includes(f.key))
})

/**
 * Preview rows with mapping applied (for step 3 table).
 */
const previewMapped = computed(() => {
	return importStore.previewRows.slice(0, 20).map(row => {
		const mapped = {}
		for (const [sourceIdx, targetKey] of Object.entries(importStore.mapping)) {
			if (targetKey && row[parseInt(sourceIdx)] !== undefined) {
				mapped[targetKey] = row[parseInt(sourceIdx)]
			}
		}
		return mapped
	})
})

/**
 * Total records to create across all bundle entities.
 */
const bundleTotalToCreate = computed(() => {
	if (!importStore.bundlePreviewResult?.results) return 0
	return importStore.bundlePreviewResult.results.reduce(
		(sum, r) => sum + (r.summary?.toCreate || 0), 0,
	)
})

function onFileSelected(event) {
	const file = event.target.files[0]
	if (!file) return

	if (file.name.toLowerCase().endsWith('.zip')) {
		importStore.uploadBundle(file)
	} else {
		importStore.uploadFile(file)
	}
}

function onEntityTypeChange(newType) {
	importStore.changeEntityType(newType)
}

function goToPreview() {
	importStore.step = 3
}

/**
 * Whether any conflict has unresolved fields.
 */
const hasUnresolvedConflicts = computed(() => {
	return importStore.conflictResolutions.some(r => r.hasUnresolved)
})

function onConflictResolutions(resolutions) {
	importStore.conflictResolutions = resolutions
}

async function onExecuteWithMerge() {
	// First execute new records, then merge conflicts
	await importStore.executeImport()
	if (importStore.conflictResolutions.some(r => Object.keys(r.mergedFields).length > 0)) {
		await importStore.executeMerge()
	}
}

// ── Inline error correction ──

const expandedErrors = reactive({})

const editableFields = computed(() => {
	return importStore.targetFields.filter(f => f.key !== 'id')
})

function toggleErrorExpand(rowIndex) {
	expandedErrors[rowIndex] = !expandedErrors[rowIndex]
}

function getCorrectedValue(rowIndex, fieldKey, originalValue) {
	const corrections = importStore.corrections[rowIndex]
	if (corrections && fieldKey in corrections) {
		return corrections[fieldKey]
	}
	return originalValue || ''
}

function onCorrectionInput(rowIndex, fieldKey, value) {
	if (!importStore.corrections[rowIndex]) {
		importStore.corrections[rowIndex] = {}
	}
	importStore.corrections[rowIndex][fieldKey] = value
}

function hasCorrections(rowIndex) {
	const c = importStore.corrections[rowIndex]
	return c && Object.keys(c).length > 0
}

const hasCorrectedRows = computed(() => {
	return Object.keys(importStore.corrections).length > 0
})

// ── Bundle inline error correction ──

const expandedBundleErrors = reactive({})

function toggleBundleErrorExpand(entityType, rowIndex) {
	const key = entityType + ':' + rowIndex
	expandedBundleErrors[key] = !expandedBundleErrors[key]
}

function isBundleErrorExpanded(entityType, rowIndex) {
	return !!expandedBundleErrors[entityType + ':' + rowIndex]
}

function getBundleEditableFields(res) {
	return (res.targetFields || []).filter(f => f.key !== 'id')
}

function getBundleCorrectedValue(entityType, rowIndex, fieldKey, originalValue) {
	const entityCorr = importStore.bundleCorrections[entityType]
	if (entityCorr && entityCorr[rowIndex] && fieldKey in entityCorr[rowIndex]) {
		return entityCorr[rowIndex][fieldKey]
	}
	return originalValue || ''
}

function onBundleCorrectionInput(entityType, rowIndex, fieldKey, value) {
	if (!importStore.bundleCorrections[entityType]) {
		importStore.bundleCorrections[entityType] = {}
	}
	if (!importStore.bundleCorrections[entityType][rowIndex]) {
		importStore.bundleCorrections[entityType][rowIndex] = {}
	}
	importStore.bundleCorrections[entityType][rowIndex][fieldKey] = value
}

function hasBundleCorrections(entityType, rowIndex) {
	const c = importStore.bundleCorrections[entityType]
	return c && c[rowIndex] && Object.keys(c[rowIndex]).length > 0
}

const hasBundleCorrectedRows = computed(() => {
	return Object.keys(importStore.bundleCorrections).length > 0
})
</script>

<style scoped>
.import-export-page {
	padding: 20px;
	max-width: 1000px;
}

.import-export-page h2 {
	margin: 0 0 16px 0;
}

.import-export-page__tabs {
	display: flex;
	gap: 0;
	margin-bottom: 24px;
	border-bottom: 2px solid var(--color-border);
}

.import-export-page__tab {
	padding: 10px 24px;
	border: none;
	background: none;
	cursor: pointer;
	font-size: 1em;
	font-weight: 500;
	color: var(--color-text-lighter);
	border-bottom: 2px solid transparent;
	margin-bottom: -2px;
	transition: color 0.15s, border-color 0.15s;
}

.import-export-page__tab:hover {
	color: var(--color-main-text);
}

.import-export-page__tab--active {
	color: var(--color-primary);
	border-bottom-color: var(--color-primary);
}

.import-export-page__section {
	min-height: 300px;
}

.import-export-page__section h3 {
	margin: 0 0 8px 0;
}

.import-export-page__hint {
	color: var(--color-text-lighter);
	font-size: 0.9em;
	margin-bottom: 20px;
}

.import-export-page__error {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 10px 14px;
	background: var(--color-error);
	color: white;
	border-radius: var(--border-radius);
	margin-bottom: 16px;
	font-size: 0.9em;
}

.import-export-page__subsection {
	margin-bottom: 24px;
}

.import-export-page__subsection h4 {
	margin: 0 0 8px 0;
}

.import-export-page__bundle-controls {
	display: flex;
	gap: 12px;
	align-items: center;
}

.import-export-page__sensitive-btn {
	border-color: var(--color-error) !important;
	color: var(--color-error) !important;
}

.import-export-page__divider {
	border: none;
	border-top: 1px solid var(--color-border);
	margin: 24px 0;
}

.import-export-page__warning-dialog {
	padding: 8px 0;
}

.import-export-page__warning-text {
	margin-bottom: 12px;
	line-height: 1.5;
}

.import-export-page__warning-actions {
	display: flex;
	justify-content: flex-end;
	gap: 12px;
	margin-top: 20px;
}

.import-export-page__export-controls {
	display: flex;
	align-items: flex-end;
	gap: 16px;
}

.import-export-page__label {
	display: flex;
	flex-direction: column;
	gap: 4px;
	font-size: 0.9em;
	font-weight: 500;
}

.import-export-page__select {
	padding: 8px 12px;
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	font-size: 1em;
	min-width: 250px;
}

/* ── Import wizard styles (unchanged) ── */
.import-wizard {
	max-width: 1000px;
}

.import-wizard__steps {
	display: flex;
	gap: 4px;
	margin-bottom: 24px;
}

.import-wizard__step {
	padding: 6px 14px;
	border-radius: var(--border-radius-pill);
	font-size: 0.85em;
	background: var(--color-background-dark);
	color: var(--color-text-lighter);
}

.import-wizard__step--active {
	background: var(--color-primary);
	color: white;
	font-weight: 600;
}

.import-wizard__step--done {
	background: var(--color-success);
	color: white;
}

.import-wizard__content {
	min-height: 300px;
}

.import-wizard__content h3 {
	margin: 0 0 8px 0;
}

.import-wizard__hint {
	color: var(--color-text-lighter);
	font-size: 0.9em;
	margin-bottom: 16px;
}

.import-wizard__error {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 10px 14px;
	background: var(--color-error);
	color: white;
	border-radius: var(--border-radius);
	margin-bottom: 16px;
	font-size: 0.9em;
}

.import-wizard__upload-area {
	margin-bottom: 20px;
}

.import-wizard__file-input-hidden {
	display: none;
}

.import-wizard__file-name {
	margin-left: 12px;
	color: var(--color-text-lighter);
	font-size: 0.9em;
}

.import-wizard__options {
	display: flex;
	gap: 24px;
	margin-top: 12px;
}

.import-wizard__option {
	display: flex;
	align-items: center;
	gap: 8px;
	font-size: 0.9em;
}

.import-wizard__select {
	padding: 4px 8px;
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	font-size: 0.9em;
}

.import-wizard__mapping-table {
	width: 100%;
	border-collapse: collapse;
	margin-bottom: 16px;
}

.import-wizard__mapping-table 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);
}

.import-wizard__mapping-table td {
	padding: 8px 12px;
	border-bottom: 1px solid var(--color-border);
}

.import-wizard__col-name {
	font-weight: 500;
}

.import-wizard__col-preview {
	color: var(--color-text-lighter);
	font-size: 0.9em;
	font-style: italic;
}

.import-wizard__checkbox {
	display: flex;
	align-items: center;
	gap: 8px;
	font-size: 0.9em;
	margin-bottom: 16px;
}

.import-wizard__preview-scroll {
	overflow-x: auto;
	margin-bottom: 16px;
}

.import-wizard__preview-table {
	width: 100%;
	border-collapse: collapse;
	font-size: 0.9em;
}

.import-wizard__preview-table th {
	text-align: left;
	padding: 6px 10px;
	font-weight: 600;
	font-size: 0.85em;
	border-bottom: 2px solid var(--color-border);
	white-space: nowrap;
}

.import-wizard__preview-table td {
	padding: 6px 10px;
	border-bottom: 1px solid var(--color-border);
}

.import-wizard__nav {
	display: flex;
	gap: 12px;
	margin-top: 20px;
	padding-top: 16px;
	border-top: 1px solid var(--color-border);
}

.import-wizard__summary {
	display: flex;
	gap: 16px;
	margin-bottom: 20px;
}

.import-wizard__summary-item {
	padding: 12px 20px;
	border-radius: var(--border-radius-large);
	text-align: center;
	min-width: 120px;
}

.import-wizard__summary-item--success {
	background: var(--color-success, #2d7b41);
	color: white;
}

.import-wizard__summary-item--warning {
	background: #664d03 !important;
	color: #fef3cd !important;
	border: 1px solid #e9d78a !important;
}

.import-wizard__summary-item--error {
	background: var(--color-error, #DB0606);
	color: white;
}

.import-wizard__section {
	margin-bottom: 20px;
}

.import-wizard__section h4 {
	margin: 0 0 8px 0;
}

.import-wizard__error-row {
	padding: 8px 12px;
	background: #5c1a1a !important;
	color: #fdd !important;
	border-radius: var(--border-radius);
	margin-bottom: 4px;
	font-size: 0.9em;
}

.import-wizard__error-row--fixable {
	cursor: pointer;
	padding: 0;
}

.import-wizard__error-header {
	display: flex;
	align-items: center;
	gap: 8px;
	padding: 8px 12px;
}

.import-wizard__error-toggle {
	flex-shrink: 0;
	width: 16px;
	font-size: 0.8em;
}

.import-wizard__error-msgs {
	flex: 1;
	opacity: 0.9;
}

.import-wizard__error-badge {
	font-size: 0.75em;
	background: #2d7b41;
	color: white;
	padding: 2px 8px;
	border-radius: 10px;
	flex-shrink: 0;
}

.import-wizard__error-fields {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
	gap: 8px;
	padding: 8px 12px 12px 36px;
	border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.import-wizard__error-field {
	display: flex;
	flex-direction: column;
	gap: 2px;
}

.import-wizard__error-field label {
	font-size: 0.8em;
	opacity: 0.8;
}

.import-wizard__error-field--required label {
	font-weight: bold;
}

.import-wizard__error-input {
	padding: 4px 8px;
	border: 1px solid rgba(255, 255, 255, 0.3);
	border-radius: var(--border-radius);
	background: rgba(255, 255, 255, 0.1);
	color: inherit;
	font-size: 0.9em;
}

.import-wizard__error-input:focus {
	outline: none;
	border-color: var(--color-primary-element);
}

.import-wizard__error-input--missing {
	border-color: #ff6b6b;
	background: rgba(255, 50, 50, 0.15);
}

.import-wizard__revalidate {
	margin-top: 12px;
}

.import-wizard__error-row ul {
	margin: 4px 0 0 20px;
	padding: 0;
}

.import-wizard__dup-row {
	padding: 6px 12px;
	background: #4a3f00 !important;
	color: #fefce8 !important;
	border-radius: var(--border-radius);
	margin-bottom: 4px;
	font-size: 0.9em;
}

.import-wizard__file-row {
	display: flex;
	align-items: center;
	gap: 12px;
	margin-top: 12px;
	margin-bottom: 12px;
}

.import-wizard__select--wide {
	min-width: 280px;
}

.import-wizard__detection {
	padding: 8px 14px;
	background: var(--color-primary-element-light);
	border-radius: var(--border-radius);
	margin-bottom: 16px;
	font-size: 0.9em;
}

.import-wizard__detection--unknown {
	color: var(--color-warning);
}

.import-wizard__entity-select {
	margin-bottom: 16px;
}

.import-wizard__warning-row {
	padding: 6px 12px;
	background: #4a3000 !important;
	color: #ffe0b2 !important;
	border-left: 3px solid var(--color-warning);
	border-radius: var(--border-radius);
	margin-bottom: 4px;
	font-size: 0.9em;
}

.import-wizard__bundle-entity {
	margin-bottom: 20px;
	padding-bottom: 16px;
	border-bottom: 1px solid var(--color-border);
}

.import-wizard__bundle-entity h4 {
	margin: 0 0 8px 0;
}

.import-wizard__status-ok {
	color: var(--color-success);
	font-weight: 500;
}

.import-wizard__status-err {
	color: var(--color-error);
	font-weight: 500;
}

.import-wizard__summary-item--merge {
	background: var(--color-primary);
	color: white;
}

.import-wizard__migration-toggle {
	margin-top: 16px;
	padding: 10px 14px;
	background: var(--color-background-dark);
	border-radius: var(--border-radius);
}

.import-wizard__migration-hint {
	padding: 8px 14px;
	background: #eff6ff;
	border-left: 3px solid var(--color-primary);
	border-radius: var(--border-radius);
	margin-top: 8px;
	font-size: 0.85em;
	color: var(--color-text-lighter);
}

.import-wizard__migration-active {
	padding: 8px 14px;
	background: var(--color-primary-element-light);
	border-radius: var(--border-radius);
	margin-bottom: 16px;
	font-weight: 500;
	font-size: 0.9em;
}

.import-wizard__ambiguous-row {
	padding: 6px 12px;
	background: #fef3c7;
	border-left: 3px solid #f59e0b;
	border-radius: var(--border-radius);
	margin-bottom: 4px;
	font-size: 0.9em;
}
</style>
