<template>
    <div class="meta-editor">
        <div v-if="loading" class="loading">Loading metadata...</div>

        <div v-else-if="error" class="error">{{ error }}</div>

        <div v-else-if="!dropName" class="error">
            No drop specified. Please run CMS with a drop name.
        </div>

        <form v-else @submit.prevent="saveMeta" class="meta-form">
            <div class="form-header">
                <h1 class="h2">Edit Metadata: {{ dropName }}</h1>
            </div>

            <!-- Name (readonly, identifier) -->
            <div class="form-group">
                <label for="name">Name (identifier)</label>
                <input
                    id="name"
                    v-model="meta.name"
                    type="text"
                    readonly
                    class="readonly"
                />
                <small>This is the drop's identifier and cannot be changed.</small>
            </div>

            <!-- Title -->
            <div class="form-group">
                <label for="title">Title</label>
                <input
                    id="title"
                    v-model="meta.title"
                    type="text"
                    required
                    placeholder="Display title"
                />
            </div>

            <!-- Published -->
            <div class="form-group checkbox-group">
                <label class="checkbox-label">
                    <input
                        id="published"
                        v-model="meta.published"
                        type="checkbox"
                        class="checkbox"
                    />
                    <span class="checkbox-text">
                        <strong>Published</strong>
                        <small>When checked, this drop will be included in the build</small>
                    </span>
                </label>
            </div>

            <!-- Description -->
            <div class="form-group">
                <label for="description">Description</label>
                <rich-text v-model="meta.description" editable />
            </div>

            <!-- Date -->
            <div class="form-group">
                <label for="date">Date</label>
                <input
                    id="date"
                    v-model="meta.date"
                    type="date"
                    required
                />
            </div>

            <!-- Tags -->
            <div class="form-group">
                <label>Tags</label>
                <div class="tags-editor">
                    <div class="tag-list">
                        <span
                            v-for="(tag, index) in meta.tags"
                            :key="index"
                            class="tag"
                        >
                            {{ tag }}
                            <button
                                type="button"
                                @click="removeTag(index)"
                                class="tag-remove"
                            >
                                ×
                            </button>
                        </span>
                    </div>
                    <div class="tag-input-wrapper">
                        <input
                            v-model="newTag"
                            type="text"
                            placeholder="Add a tag"
                            @keypress.enter.prevent="addTag"
                        />
                        <btn type="button" @click="addTag">
                            Add Tag
                        </btn>
                    </div>
                </div>
            </div>

            <!-- Actions -->
            <div class="form-actions">
                <btn type="submit" :disabled="saving">
                    {{ saving ? 'Saving...' : 'Save Changes' }}
                </btn>
                <btn type="button" @click="loadMeta">
                    Reset
                </btn>
            </div>

            <div v-if="saveSuccess" class="success-wrapper">
                <div class="success-message">
                    <span>
                        ✓ Changes saved successfully!
                    </span>
                </div>
            </div>
        </form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import RichText from '@shared/RichText.vue'
import Btn from '@shared/Btn.vue'

const dropName = ref(null)
const meta = ref({
    name: '',
    title: '',
    description: '',
    date: '',
    tags: [],
    links: [],
    notes: '',
    published: false,
})

const loading = ref(true)
const error = ref(null)
const saving = ref(false)
const saveSuccess = ref(false)
const newTag = ref('')

// Load drop info
const loadDropInfo = async () => {
    try {
        const res = await fetch('/api/drop-info')
        const data = await res.json()
        dropName.value = data.dropName
    } catch (err) {
        console.error('Failed to load drop info:', err)
    }
}

// Load metadata
const loadMeta = async () => {
    loading.value = true
    error.value = null
    try {
        const res = await fetch('/api/meta')
        if (!res.ok) {
            throw new Error(`Failed to load metadata: ${res.statusText}`)
        }
        const data = await res.json()
        meta.value = data
    } catch (err) {
        error.value = err.message
    } finally {
        loading.value = false
    }
}

// Save metadata
const saveMeta = async () => {
    saving.value = true
    saveSuccess.value = false
    error.value = null
    try {
        const res = await fetch('/api/meta', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(meta.value),
        })
        if (!res.ok) {
            throw new Error(`Failed to save metadata: ${res.statusText}`)
        }
        saveSuccess.value = true
        setTimeout(() => {
            saveSuccess.value = false
        }, 3000)
    } catch (err) {
        error.value = err.message
    } finally {
        saving.value = false
    }
}

// Tag management
const addTag = () => {
    const tag = newTag.value.trim()
    if (tag && !meta.value.tags.includes(tag)) {
        meta.value.tags.push(tag)
        newTag.value = ''
    }
}
const removeTag = (index) => {
    meta.value.tags.splice(index, 1)
}

onMounted(async () => {
    await loadDropInfo()
    if (dropName.value) {
        await loadMeta()
    } else {
        loading.value = false
    }
})
</script>

<style lang="scss">
.meta-editor {
    max-width: rs(800px);
    margin: 0 auto;
    padding: 2rem;

    .loading,
    .error {
        text-align: center;
        padding: 2rem;
    }
    .error {
        color: var(--clay);
    }
    .meta-form {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }
    .form-header {
        margin-bottom: 1rem;

        h1 {
            margin: 0 0 0.5rem;
        }

        .drop-name {
            margin: 0;
            color: var(--theme-grey);
        }
    }

    .form-group {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;

        input,
        textarea, .rich-text {
            padding: 0.75rem;
            border: 1px solid var(--theme-grey);
            border-radius: rs(10px);
            font-family: inherit;

            &:focus {
                outline: none;
                border-color: var(--sea);
            }
            &.readonly {
                background: var(--theme-shade);
                pointer-events: none;
            }
        }
        textarea {
            resize: vertical;
        }
        small {
            color: var(--theme-grey);
        }
    }

    .tags-editor {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;

        .tag-list {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
        }
        .tag {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: rs(6px) rs(16px);
            background: var(--theme-shade);
            border-radius: rs(8px);
            @include label;

            .tag-remove {
                background: none;
                border: none;
                font-size: 1.5rem;
                line-height: 1;
                cursor: pointer;
                padding: 0;

                &:hover {
                    color: var(--theme-contrast);
                }
            }
        }
        .tag-input-wrapper {
            display: flex;
            gap: 0.5rem;
            align-items: center;
        }
    }

    .checkbox-group {
        .checkbox-label {
            display: flex;
            align-items: flex-start;
            gap: 0.75rem;
            cursor: pointer;
            padding: 1rem;
            border: 1px solid var(--theme-grey);
            border-radius: rs(10px);
            transition: border-color 0.2s;

            &:hover {
                border-color: var(--sea);
            }
            .checkbox {
                width: 20px;
                height: 20px;
                margin-top: 0.125rem;
                cursor: pointer;
                accent-color: var(--sea);

                &:checked {
                    background: var(--theme-contrast);
                }
            }
            .checkbox-text {
                display: flex;
                flex-direction: column;
                gap: 0.25rem;
                flex: 1;

                strong {
                    display: block;
                }

                small {
                    color: var(--theme-grey);
                }
            }
        }
    }

    .form-actions {
        display: flex;
        gap: 1rem;
        margin-top: 1rem;
    }

    .success-wrapper {
        position: fixed;
        bottom: 0;
        left: 50%;
        width: rs(800px);
        padding: 2rem;
        transform: translateX(-50%);
        display: flex;
        justify-content: flex-end;

        .success-message {
            padding: 1rem;
            background: var(--forest-shade);
            border: 1px solid var(--forest);
            border-radius: rs(8px);
            color: var(--forest);
            text-align: center;
            animation: fadeIn 0.3s;
        }
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>
