<template>
    <div>
        <h1>Управление модпаками</h1>

        <div class="import-section">
            <h2>Импорт нового модпака</h2>
            <form @submit.prevent="handleImport" class="import-form">
                <div class="form-group">
                    <label>Тип сборки</label>
                    <select v-model="form.importerType">
                        <option value="simple">Простой ZIP</option>
                        <option value="curseforge">CurseForge</option>
                        <option value="modrinth" disabled>Modrinth (в разработке)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Метод импорта</label>
                    <div class="radio-group">
                        <label><input type="radio" v-model="form.importMethod" value="file" /> Файл</label>
                        <label
                            ><input type="radio" v-model="form.importMethod" value="url" :disabled="form.importerType !== 'curseforge'" />
                            URL</label
                        >
                    </div>
                </div>

                <!-- Поля для метаданных -->
                <div class="form-group">
                    <label for="name">Системное имя (латиница, без пробелов)</label>
                    <input id="name" v-model="form.name" type="text" required pattern="^[a-zA-Z0-9_]+$" />
                </div>
                <div class="form-group">
                    <label for="displayName">Отображаемое имя</label>
                    <input id="displayName" v-model="form.displayName" type="text" required />
                </div>
                <div class="form-group">
                    <label for="mcVersion">Версия Minecraft</label>
                    <input id="mcVersion" v-model="form.mcVersion" type="text" required />
                </div>

                <!-- Поля для источника -->
                <div v-if="form.importMethod === 'file'" class="form-group">
                    <label for="modpack-file">Файл модпака (.zip)</label>
                    <input id="modpack-file" type="file" @change="onFileSelected" :required="form.importMethod === 'file'" accept=".zip" />
                </div>
                <div v-if="form.importMethod === 'url'" class="form-group">
                    <label for="sourceUrl">URL страницы модпака на CurseForge</label>
                    <input id="sourceUrl" v-model="form.sourceUrl" type="url" :required="form.importMethod === 'url'" />
                </div>

                <div v-if="error" class="error-message">{{ error }}</div>
                <div v-if="successMessage" class="success-message">{{ successMessage }}</div>

                <button type="submit" :disabled="isLoading">
                    {{ isLoading ? "Импорт..." : "Импортировать" }}
                </button>
            </form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import apiClient from "@/api/axios";

const form = reactive({
    name: "",
    displayName: "",
    mcVersion: "",
    file: null as File | null,
    importerType: "simple",
    importMethod: "file",
    sourceUrl: "",
});

const isLoading = ref(false);
const error = ref<string | null>(null);
const successMessage = ref<string | null>(null);

watch(
    () => form.importerType,
    (newType) => {
        if (newType !== "curseforge" && form.importMethod === "url") {
            form.importMethod = "file";
        }
    },
);

const onFileSelected = (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files[0]) {
        form.file = target.files[0];
    }
};

const handleImport = async () => {
    if (form.importMethod === "file" && !form.file) {
        error.value = "Пожалуйста, выберите файл для импорта.";
        return;
    }
    if (form.importMethod === "url" && !form.sourceUrl) {
        error.value = "Пожалуйста, введите URL.";
        return;
    }

    isLoading.value = true;
    error.value = null;
    successMessage.value = null;

    const formData = new FormData();
    formData.append("name", form.name);
    formData.append("displayName", form.displayName);
    formData.append("mcVersion", form.mcVersion);
    formData.append("importerType", form.importerType);
    formData.append("importMethod", form.importMethod);

    if (form.importMethod === "file" && form.file) {
        formData.append("file", form.file);
    } else if (form.importMethod === "url") {
        formData.append("sourceUrl", form.sourceUrl);
    }

    try {
        const response = await apiClient.post("/admin/modpacks/import", formData, {
            headers: {
                "Content-Type": "multipart/form-data",
            },
        });
        successMessage.value = response.data;
    } catch (e: any) {
        error.value = e.response?.data || "Произошла ошибка при импорте.";
    } finally {
        isLoading.value = false;
    }
};
</script>

<style scoped>
.import-section {
    max-width: 600px;
    margin-top: 2rem;
    padding: 2rem;
    border: 1px solid #ddd;
    border-radius: 8px;
}
.import-form .form-group {
    margin-bottom: 1rem;
}
.import-form label {
    display: block;
    margin-bottom: 0.5rem;
}
.import-form input,
.import-form select {
    width: 100%;
    padding: 0.5rem;
    box-sizing: border-box;
}
.radio-group label {
    display: inline-block;
    margin-right: 1rem;
}
.error-message,
.success-message {
    margin-top: 1rem;
    padding: 0.75rem;
    border-radius: 4px;
    text-align: center;
}
.error-message {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}
.success-message {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}
button {
    padding: 0.75rem 1.5rem;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
button:disabled {
    background-color: #ccc;
}
</style>
