<script lang="ts">
    import { enhance } from '$app/forms';
    import PersonTypeahead from '$lib/components/PersonTypeahead.svelte';

    let { data, form } = $props();

    const person = $derived(data.person);
    const documents = $derived(data.documents);

    let editMode = $state(false);
    let mergeTargetId = $state('');
    let showMergeConfirm = $state(false);

    $effect(() => {
        if (form?.updated) editMode = false;
    });

    $effect(() => {
        // Reset merge state whenever person changes
        person.id;
        mergeTargetId = '';
        showMergeConfirm = false;
    });
</script>

<div class="max-w-4xl mx-auto py-10 px-4">

    <!-- Back Link -->
    <div class="mb-6">
        <a href="/persons" class="inline-flex items-center text-xs font-bold uppercase tracking-widest text-gray-500 hover:text-brand-navy transition-colors group">
            <img src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Arrow/Arrow-Left-MD.svg" alt="" aria-hidden="true" class="w-4 h-4 mr-2 transform group-hover:-translate-x-1 transition-transform" />
            Zurück zur Übersicht
        </a>
    </div>

    <!-- Header / Metadata Card -->
    <div class="bg-white shadow-sm border border-brand-sand rounded-sm overflow-hidden mb-10">
        <div class="h-2 bg-brand-navy w-full"></div>

        <div class="p-8 md:p-10">
            {#if editMode}
                <!-- Edit Form -->
                <form method="POST" action="?/update" use:enhance>
                    <div class="flex flex-col gap-6">
                        <h2 class="text-xl font-serif text-brand-navy border-b border-gray-100 pb-3">Person bearbeiten</h2>

                        {#if form?.updateError}
                            <p class="text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2">{form.updateError}</p>
                        {/if}

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="firstName" class="block text-xs font-bold uppercase tracking-widest text-gray-400 mb-1">Vorname *</label>
                                <input
                                    id="firstName"
                                    name="firstName"
                                    type="text"
                                    required
                                    value={person.firstName}
                                    class="block w-full border border-gray-300 rounded px-3 py-2 font-serif text-brand-navy focus:outline-none focus:border-brand-navy"
                                />
                            </div>
                            <div>
                                <label for="lastName" class="block text-xs font-bold uppercase tracking-widest text-gray-400 mb-1">Nachname *</label>
                                <input
                                    id="lastName"
                                    name="lastName"
                                    type="text"
                                    required
                                    value={person.lastName}
                                    class="block w-full border border-gray-300 rounded px-3 py-2 font-serif text-brand-navy focus:outline-none focus:border-brand-navy"
                                />
                            </div>
                            <div class="md:col-span-2">
                                <label for="alias" class="block text-xs font-bold uppercase tracking-widest text-gray-400 mb-1">Rufname / Alias</label>
                                <input
                                    id="alias"
                                    name="alias"
                                    type="text"
                                    value={person.alias ?? ''}
                                    class="block w-full border border-gray-300 rounded px-3 py-2 font-serif text-brand-navy focus:outline-none focus:border-brand-navy"
                                />
                            </div>
                        </div>

                        <div class="flex gap-3">
                            <button type="submit" class="px-5 py-2 bg-brand-navy text-white text-sm font-bold uppercase tracking-widest rounded hover:bg-brand-navy/80 transition-colors">
                                Speichern
                            </button>
                            <button type="button" onclick={() => (editMode = false)} class="px-5 py-2 border border-gray-300 text-gray-600 text-sm font-bold uppercase tracking-widest rounded hover:bg-gray-50 transition-colors">
                                Abbrechen
                            </button>
                        </div>
                    </div>
                </form>
            {:else}
                <!-- View Mode -->
                <div class="flex flex-col md:flex-row gap-8 items-start">
                    <div class="flex-shrink-0">
                        <div class="w-24 h-24 rounded-full bg-brand-sand/30 flex items-center justify-center text-brand-navy border border-brand-sand">
                            <span class="font-serif text-3xl">{person.firstName[0]}{person.lastName[0]}</span>
                        </div>
                    </div>

                    <div class="flex-1 w-full">
                        <div class="flex items-start justify-between mb-8 border-b border-gray-100 pb-4">
                            <h1 class="text-4xl font-serif text-brand-navy">
                                {person.firstName} {person.lastName}
                            </h1>
                            <button onclick={() => (editMode = true)} class="ml-4 flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold uppercase tracking-widest border border-gray-300 text-gray-500 rounded hover:border-brand-navy hover:text-brand-navy transition-colors">
                                <img src="/degruyter-icons/Simple/Small-16px/SVG/Action/Edit-Content-SM.svg" alt="" aria-hidden="true" class="w-3.5 h-3.5" />
                                Bearbeiten
                            </button>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                            <div>
                                <span class="block text-xs font-bold font-sans text-gray-400 uppercase tracking-widest mb-1">Voller Name</span>
                                <span class="block text-lg font-serif text-brand-navy">{person.firstName} {person.lastName}</span>
                            </div>

                            {#if person.alias}
                            <div>
                                <span class="block text-xs font-bold font-sans text-gray-400 uppercase tracking-widest mb-1">Rufname / Alias</span>
                                <span class="block text-lg font-serif text-brand-navy italic">"{person.alias}"</span>
                            </div>
                            {/if}
                        </div>
                    </div>
                </div>
            {/if}
        </div>
    </div>

    <!-- Merge Section -->
    {#key person.id}
    <div class="bg-white shadow-sm border border-brand-sand rounded-sm overflow-hidden mb-10">
        <div class="p-6 md:p-8">
            <h2 class="text-lg font-serif text-brand-navy mb-1">Person zusammenführen</h2>
            <p class="text-sm text-gray-500 font-sans mb-5">
                Diese Person wird in die gewählte Zielperson überführt. Alle Dokumente und Verknüpfungen werden übertragen, danach wird diese Person gelöscht.
            </p>

            {#if form?.mergeError}
                <p class="text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2 mb-4">{form.mergeError}</p>
            {/if}

            <form method="POST" action="?/merge" use:enhance>
                <input type="hidden" name="targetPersonId" bind:value={mergeTargetId} />

                <div class="flex flex-col sm:flex-row gap-3 items-end">
                    <div class="flex-1">
                        <PersonTypeahead
                            name="_targetPersonDisplay"
                            label="Zusammenführen mit"
                            value={mergeTargetId}
                            onchange={(value) => { mergeTargetId = value; showMergeConfirm = false; }}
                        />
                    </div>

                    {#if !showMergeConfirm}
                        <button
                            type="button"
                            disabled={!mergeTargetId}
                            onclick={() => (showMergeConfirm = true)}
                            class="px-4 py-2 text-sm font-bold uppercase tracking-widest border border-red-300 text-red-600 rounded hover:bg-red-50 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
                        >
                            Zusammenführen
                        </button>
                    {:else}
                        <div class="flex gap-2">
                            <button
                                type="submit"
                                class="px-4 py-2 text-sm font-bold uppercase tracking-widest bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
                            >
                                Ja, zusammenführen
                            </button>
                            <button
                                type="button"
                                onclick={() => (showMergeConfirm = false)}
                                class="px-4 py-2 text-sm font-bold uppercase tracking-widest border border-gray-300 text-gray-500 rounded hover:bg-gray-50 transition-colors"
                            >
                                Abbrechen
                            </button>
                        </div>
                    {/if}
                </div>

                {#if showMergeConfirm}
                    <p class="mt-3 text-sm text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2">
                        Achtung: Diese Aktion ist nicht rückgängig zu machen. <strong>{person.firstName} {person.lastName}</strong> wird gelöscht.
                    </p>
                {/if}
            </form>
        </div>
    </div>
    {/key}

    <!-- Linked Documents Section -->
    <div>
        <div class="flex items-center justify-between mb-6 border-b border-brand-navy/10 pb-2">
            <h2 class="text-xl font-serif text-brand-navy">Gesendete Dokumente</h2>
            <span class="bg-brand-navy text-white text-xs font-bold px-2 py-1 rounded-full">
                {documents.length}
            </span>
        </div>

        {#if documents.length === 0}
            <div class="p-12 text-center bg-white border border-brand-sand border-dashed rounded-sm">
                <p class="text-gray-500 font-sans">Diese Person ist noch nicht als Absender verknüpft.</p>
            </div>
        {:else}
            <ul class="space-y-3">
                {#each documents as doc}
                    <li class="group">
                        <a href="/documents/{doc.id}" class="block bg-white border border-brand-sand p-4 hover:border-brand-navy hover:shadow-md transition-all duration-200">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-4 overflow-hidden">
                                    <div class="flex-shrink-0 h-10 w-10 bg-brand-sand/20 text-brand-navy rounded flex items-center justify-center group-hover:bg-brand-mint group-hover:text-brand-navy transition-colors">
                                        <img src="/degruyter-icons/Simple/Medium-24px/SVG/Action/PDF-Document-MD.svg" alt="" aria-hidden="true" class="w-5 h-5" />
                                    </div>
                                    <div class="min-w-0">
                                        <div class="font-serif text-base font-medium text-brand-navy truncate group-hover:underline decoration-brand-mint decoration-2 underline-offset-2">
                                            {doc.title || doc.originalFilename}
                                        </div>
                                        <div class="flex items-center text-xs font-sans text-gray-500 mt-0.5 space-x-2">
                                            <span>{doc.documentDate ? new Intl.DateTimeFormat('de-DE', { day: 'numeric', month: 'long', year: 'numeric' }).format(new Date(doc.documentDate + 'T12:00:00')) : 'Kein Datum'}</span>
                                            {#if doc.location}
                                                <span class="text-brand-mint">•</span>
                                                <span>{doc.location}</span>
                                            {/if}
                                        </div>
                                    </div>
                                </div>
                                <div class="flex items-center flex-shrink-0 pl-4">
                                    <span class="hidden sm:inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide border
                                        {doc.status === 'UPLOADED'
                                            ? 'bg-brand-mint/20 text-brand-navy border-brand-mint/50'
                                            : 'bg-yellow-50 text-yellow-800 border-yellow-200'}">
                                        {doc.status}
                                    </span>
                                    <img src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Arrow/Arrow-Right-MD.svg" alt="" aria-hidden="true" class="h-5 w-5 ml-4 opacity-40 group-hover:opacity-100 transition-opacity" />
                                </div>
                            </div>
                        </a>
                    </li>
                {/each}
            </ul>
        {/if}
    </div>

</div>
