<template>
    <div class="contextUpload">
        <div class="contextUpload__card">
            <h2 class="contextUpload__title">Upload Context Files</h2>
            <div
                class="contextUpload__dropzone"
                :class="{ 'contextUpload__dropzone--active': dragActive }"
                @dragenter.prevent.stop="handleDragEnter"
                @dragleave.prevent.stop="handleDragLeave"
                @dragover.prevent.stop="handleDragOver"
                @drop.prevent.stop="handleDrop"
            >
                <input
                    ref="fileInput"
                    type="file"
                    multiple
                    class="contextUpload__input"
                    @change="handleFileSelect"
                />

                <svg
                    class="contextUpload__icon"
                    stroke="currentColor"
                    fill="none"
                    viewBox="0 0 48 48"
                >
                    <path
                        d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                    />
                </svg>

                <p class="contextUpload__dropzone__text">
                    Drag and drop (PDF/TXT/Markdown) files here, or
                    <button
                        type="button"
                        class="contextUpload__browseBtn"
                        @click="triggerFileInput"
                    >
                        browse
                    </button>
                </p>
                <p class="contextUpload__dropzone-hint">
                    Upload files to add context to the agent
                </p>
            </div>

            <!-- File List -->
            <div v-if="files.length > 0" class="contextUpload__list__container">
                <div class="contextUpload__list__header">
                    <h3 class="contextUpload__list__title">
                        Selected Files ({{ files.length }})
                    </h3>
                    <button
                        class="contextUpload__clearBtn"
                        @click="clearAll"
                    >
                        Clear all
                    </button>
                </div>

                <ul class="contextUpload__list">
                    <li
                        v-for="(file, index) in files"
                        :key="index"
                        class="contextUpload__list__item"
                    >
                        <div class="contextUpload__file">
                            <svg
                                class="contextUpload__file__icon"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                    stroke-width="2"
                                    d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                                />
                            </svg>
                            <div class="contextUpload__fileDetails">
                                <p class="contextUpload__fileDetails__name">{{ file.name }}</p>
                                <p class="contextUpload__fileDetails__size">{{ formatFileSize(file.size) }}</p>
                            </div>
                        </div>

                        <div
                            v-if="uploadProgress[index] !== undefined"
                            class="contextUpload__progress"
                        >
                            <div class="contextUpload__progress__bar">
                                <div
                                    class="contextUpload__progress__fill"
                                    :style="{ width: uploadProgress[index] + '%' }"
                                />
                            </div>
                        </div>

                        <button
                            class="contextUpload__removeBtn"
                            :disabled="uploading"
                            @click="removeFile(index)"
                        >
                            <svg
                                class="contextUpload__removeIcon"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                    stroke-width="2"
                                    d="M6 18L18 6M6 6l12 12"
                                />
                            </svg>
                        </button>
                    </li>
                </ul>
            </div>

            <!-- Upload Results -->
            <div v-if="uploadResults.length > 0" class="contextUpload__results">
                <h4 class="contextUpload__results__title">Upload Results</h4>
                <ul class="contextUpload__results__list">
                    <li
                        v-for="(result, index) in uploadResults"
                        :key="index"
                        class="contextUpload__result__item"
                        :class="{
              'contextUpload__result__item--success': result.success,
              'contextUpload__result__item--error': !result.success
            }"
                    >
                        <svg
                            v-if="result.success"
                            class="contextUpload__result__icon"
                            fill="currentColor"
                            viewBox="0 0 20 20"
                        >
                            <path
                                fill-rule="evenodd"
                                d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                                clip-rule="evenodd"
                            />
                        </svg>
                        <svg
                            v-else
                            class="contextUpload__result__icon"
                            fill="currentColor"
                            viewBox="0 0 20 20"
                        >
                            <path
                                fill-rule="evenodd"
                                d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                                clip-rule="evenodd"
                            />
                        </svg>
                        <span class="contextUpload__result__name">{{ result.name }}</span>
                        <span v-if="result.error" class="contextUpload__result__error">
              ({{ result.error }})
            </span>
                    </li>
                </ul>
            </div>

            <!-- Upload Button -->
            <button
                class="contextUpload__submitBtn"
                :class="{ 'contextUpload__submitBtn--disabled': files.length === 0 || uploading }"
                :disabled="files.length === 0 || uploading"
                @click="uploadFiles"
            >
        <span v-if="uploading" class="contextUpload__submitContent">
          <svg
              class="contextUpload__spinner"
              fill="none"
              viewBox="0 0 24 24"
          >
            <circle
                class="contextUpload__spinner__track"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="4"
            />
            <path
                class="contextUpload__spinner__head"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
            />
          </svg>
          Uploading...
        </span>
                <span v-else>{{ uploadButtonText }}</span>
            </button>
        </div>
    </div>
</template>

<script>
export default {
    name: 'Context',

    data() {
        return {
            files: [],
            uploading: false,
            uploadProgress: {},
            uploadResults: [],
            dragActive: false
        };
    },

    computed: {
        uploadButtonText() {
            if (this.files.length === 0) {
                return 'Upload Files';
            }
            return `Upload ${this.files.length} File${this.files.length > 1 ? 's' : ''}`;
        }
    },

    methods: {
        handleDragEnter() {
            this.dragActive = true;
        },

        handleDragLeave() {
            this.dragActive = false;
        },

        handleDragOver() {
            this.dragActive = true;
        },

        handleDrop(e) {
            this.dragActive = false;
            const droppedFiles = Array.from(e.dataTransfer.files);
            if (droppedFiles.length > 0) {
                this.files = [...this.files, ...droppedFiles];
            }
        },

        handleFileSelect(e) {
            const selectedFiles = Array.from(e.target.files);
            if (selectedFiles.length > 0) {
                this.files = [...this.files, ...selectedFiles];
            }
            // Reset input to allow selecting the same file again
            e.target.value = '';
        },

        triggerFileInput() {
            this.$refs.fileInput.click();
        },

        removeFile(index) {
            this.files = this.files.filter((_, i) => i !== index);
        },

        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        },

        async uploadFiles() {
            if (this.files.length === 0) return;

            this.uploading = true;
            this.uploadResults = [];
            const results = [];

            for (let i = 0; i < this.files.length; i++) {
                const file = this.files[i];
                const formData = new FormData();
                formData.append('file', file);

                try {
                    this.$set(this.uploadProgress, i, 0);

                    const response = await fetch('/admin/agent/settings/context/add', {
                        method: 'POST',
                        body: formData
                    });

                    if (response.ok) {
                        this.$set(this.uploadProgress, i, 100);
                        results.push({ name: file.name, success: true });
                    } else {
                        const errorText = await response.text();
                        results.push({
                            name: file.name,
                            success: false,
                            error: errorText || 'Upload failed'
                        });
                    }
                } catch (error) {
                    results.push({
                        name: file.name,
                        success: false,
                        error: error.message
                    });
                }
            }

            this.uploadResults = results;
            this.uploading = false;

            const successfulUploads = results.filter((r) => r.success).length;
            if (successfulUploads === this.files.length) {
                this.files = [];
                this.uploadProgress = {};
            }
        },

        clearAll() {
            this.files = [];
            this.uploadProgress = {};
            this.uploadResults = [];
        }
    }
};
</script>

<style lang="less">
.contextUpload {
    width: 100%;
    max-width: 42rem;
    margin-left: auto;
    margin-right: auto;
    padding: 1.5rem;

    &__card {
        background-color: #ffffff;
        border-radius: 0.75rem;
        padding: 1.5rem;
    }

    &__title {
        font-size: 1.5rem;
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 1.5rem;
        margin-top: 0;
    }

    /* Dropzone Element */
    &__dropzone {
        position: relative;
        border: 2px dashed #d1d5db;
        border-radius: 0.5rem;
        padding: 2rem;
        text-align: center;
        transition: border-color 0.2s, background-color 0.2s;

        &:hover {
            border-color: #9ca3af;
        }

        &--active {
            border-color: #3b82f6;
            background-color: #eff6ff;
        }

        &__text {
            margin-top: 1rem;
            font-size: 1.125rem;
            color: #4b5563;
            margin-bottom: 0;
        }
    }

    &__input {
        display: none;
    }

    &__icon {
        margin-left: auto;
        margin-right: auto;
        height: 3rem;
        width: 3rem;
        color: #9ca3af;
    }

    &__browseBtn {
        background: none;
        border: none;
        color: #2563eb;
        font-weight: 500;
        text-decoration: underline;
        cursor: pointer;
        font-size: inherit;
        padding: 0;

        &:hover {
            color: #1d4ed8;
        }
    }

    &__dropzone-hint {
        margin-top: 0.5rem;
        font-size: 0.875rem;
        color: #6b7280;
        margin-bottom: 0;
    }


    &__list {
        list-style: none;
        padding: 0;
        margin: 0;
        max-height: 15rem;
        overflow-y: auto;

        &__container {
            margin-top: 1.5rem;
        }

        &__header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 0.75rem;
        }

        &__title {
            font-size: 1.125rem;
            font-weight: 500;
            color: #374151;
            margin: 0;
        }

        &__item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0.75rem;
            background-color: #f9fafb;
            border-radius: 0.5rem;
            margin-bottom: 0.5rem;

            &:last-child {
                margin-bottom: 0;
            }
        }
    }



    &__clearBtn {
        background: none;
        border: none;
        font-size: 0.875rem;
        color: #dc2626;
        cursor: pointer;
        padding: 0;

        &:hover {
            color: #b91c1c;
        }
    }



    &__file {
        display: flex;
        align-items: center;
        min-width: 0;
        flex: 1;

        &__icon {
            height: 1.25rem;
            width: 1.25rem;
            color: #9ca3af;
            margin-right: 0.75rem;
            flex-shrink: 0;
        }
    }

    &__fileDetails {
        min-width: 0;
        flex: 1;

        &__name {
            font-size: 0.875rem;
            font-weight: 500;
            color: #374151;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin: 0;
        }

        &__size {
            font-size: 0.75rem;
            color: #6b7280;
            margin: 0;
        }
    }

    /* Progress Element */
    &__progress {
        margin-left: 0.75rem;
        margin-right: 0.75rem;
        width: 5rem;

        &__bar {
            background-color: #e5e7eb;
            border-radius: 9999px;
            height: 0.5rem;
        }

        &__fill {
            background-color: #2563eb;
            height: 0.5rem;
            border-radius: 9999px;
            transition: width 0.3s;
        }
    }

    &__removeBtn {
        margin-left: 0.5rem;
        padding: 0.25rem;
        background: none;
        border: none;
        color: #9ca3af;
        cursor: pointer;

        &:hover {
            color: #ef4444;
        }

        &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    }

    &__removeIcon {
        height: 1.25rem;
        width: 1.25rem;
    }

    /* Results Element */
    &__results {
        margin-top: 1rem;
        padding: 1rem;
        border-radius: 0.5rem;
        background-color: #f9fafb;

        &__title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #374151;
            margin: 0 0 0.5rem 0;
        }

        &__list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
    }

    &__result {
        &__item {
            font-size: 0.875rem;
            display: flex;
            align-items: center;
            margin-bottom: 0.25rem;


            &:last-child {
                margin-bottom: 0;
            }

            &--success {
                color: #16a34a;
            }

            &--error {
                color: #dc2626;
            }
        }

        &__icon {
            height: 1rem;
            width: 1rem;
            margin-right: 0.5rem;
            flex-shrink: 0;
        }

        &__name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        &__error {
            margin-left: 0.5rem;
            font-size: 0.75rem;
        }
    }

    /* Submit Button Element */
    &__submitBtn {
        margin-top: 1.5rem;
        width: 100%;
        padding: 0.75rem 1rem;
        border-radius: 0.5rem;
        font-weight: 500;
        color: #ffffff;
        background-color: #2563eb;
        border: none;
        cursor: pointer;
        transition: background-color 0.2s;
        font-size: 1rem;

        &:hover:not(:disabled) {
            background-color: #1d4ed8;
        }

        &--disabled {
            background-color: #d1d5db;
            cursor: not-allowed;
        }
    }

    &__submitContent {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    &__spinner {
        animation: spin 1s linear infinite;
        margin-left: -0.25rem;
        margin-right: 0.75rem;
        height: 1.25rem;
        width: 1.25rem;
        color: #ffffff;

        &__track {
            opacity: 0.25;
        }

        &__head {
            opacity: 0.75;
        }
    }

    @keyframes spin {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }
}
</style>
