<template>
    <div>
        <!-- Form -->
        <form @submit.prevent="handleSubmit" class="space-y-6">
            <!-- Base URL -->
            <div>
                <label for="baseUrl" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Base URL
                </label>
                <input
                    id="baseUrl"
                    v-model="form.baseUrl"
                    type="url"
                    required
                    class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                    placeholder="https://example.com" />
            </div>

            <!-- Chapter URL Format -->
            <div class="border-t border-gray-200 dark:border-gray-700 pt-6">
                <label for="chapterUrlFormat" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Chapter URL Format <span class="text-gray-500">({slug}, {chapterNumber})</span>
                </label>
                <input
                    id="chapterUrlFormat"
                    v-model="form.chapterUrlFormat"
                    type="text"
                    required
                    class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                    placeholder="https://example.com/manga/{slug}-{chapterNumber}/" />
            </div>

            <!-- Selectors -->
            <div class="border-t border-gray-200 dark:border-gray-700 pt-6 space-y-4">
                <div>
                    <label for="imageSelector" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Image Selector
                    </label>
                    <input
                        id="imageSelector"
                        v-model="form.imageSelector"
                        type="text"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                        placeholder=".reading-content .page-break img" />
                </div>

                <div>
                    <label for="nextPageSelector" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Next Page Selector <span class="text-gray-500">(laisser vide si lecteur vertical)</span>
                    </label>
                    <input
                        id="nextPageSelector"
                        v-model="form.nextPageSelector"
                        type="text"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                        placeholder=".next-page" />
                </div>

                <div>
                    <label for="chapterSelector" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Chapter Selector <span class="text-gray-500">(requis pour le scraping Javascript)</span>
                    </label>
                    <input
                        id="chapterSelector"
                        v-model="form.chapterSelector"
                        type="text"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                        placeholder=".chapter-selector" />
                </div>
            </div>

            <!-- Scraping Type + Token -->
            <div class="border-t border-gray-200 dark:border-gray-700 pt-6 space-y-4">
                <div>
                    <label for="scrapingType" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Scraping Type
                    </label>
                    <select
                        id="scrapingType"
                        v-model="form.scrapingType"
                        required
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white">
                        <option value="html">HTML</option>
                        <option value="javascript">Javascript</option>
                    </select>
                </div>

                <div>
                    <label for="token" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Token
                    </label>
                    <input
                        id="token"
                        v-model="form.token"
                        type="text"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                        placeholder="Optional authentication token" />
                </div>
            </div>

            <!-- Error message -->
            <div v-if="error" class="border-t border-gray-200 dark:border-gray-700 pt-6 text-red-600 dark:text-red-400 text-sm">
                {{ error }}
            </div>
        </form>

        <!-- Test Configuration Section -->
        <div class="border-t border-gray-200 dark:border-gray-700 pt-6 mt-6">
            <div class="flex items-center space-x-2 mb-6">
                <WrenchScrewdriverIcon class="w-5 h-5 text-gray-600 dark:text-gray-400" />
                <h3 class="text-sm font-medium text-gray-900 dark:text-white">Configuration de test (health check)</h3>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                    <label for="testSlug" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Manga Slug <span class="text-gray-500">(enregistré)</span>
                    </label>
                    <input
                        id="testSlug"
                        v-model="form.testSlug"
                        type="text"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                        placeholder="manga-slug" />
                </div>

                <div>
                    <label for="testChapterNumber" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Numéro de chapitre <span class="text-gray-500">(enregistré)</span>
                    </label>
                    <input
                        id="testChapterNumber"
                        v-model="form.testChapterNumber"
                        type="number"
                        step="0.1"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                        placeholder="1" />
                </div>
            </div>

            <!-- Preview URL -->
            <div v-if="generatedTestUrl" class="mb-4 border-t border-gray-200 dark:border-gray-700 pt-4">
                <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">URL qui sera testée</p>
                <code class="text-xs text-gray-700 dark:text-gray-300 break-all">{{ generatedTestUrl }}</code>
            </div>

            <button
                type="button"
                @click="testConfiguration"
                :disabled="testing || !canTest"
                class="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-medium transition-colors duration-200 flex items-center justify-center space-x-2">
                <ArrowPathIcon v-if="testing" class="w-4 h-4 animate-spin" />
                <PlayIcon v-else class="w-4 h-4" />
                <span>Tester maintenant</span>
            </button>
        </div>
    </div>
</template>

<script setup>
import {
    ArrowPathIcon,
    PlayIcon,
    WrenchScrewdriverIcon
} from '@heroicons/vue/24/outline';
import { computed, ref, watch } from 'vue';

const props = defineProps({
    source: {
        type: Object,
        default: null
    },
    saving: {
        type: Boolean,
        default: false
    },
    error: {
        type: String,
        default: null
    }
});

const emit = defineEmits(['submit', 'test']);

const isEditing = computed(() => !!props.source);

const form = ref({
    baseUrl: '',
    imageSelector: '',
    chapterUrlFormat: '',
    nextPageSelector: '',
    chapterSelector: '',
    scrapingType: 'html',
    token: '',
    testSlug: '',
    testChapterNumber: '',
});

const testing = ref(false);

const canTest = computed(() => {
    return form.value.baseUrl &&
           form.value.chapterUrlFormat &&
           form.value.testSlug &&
           form.value.testChapterNumber;
});

const generatedTestUrl = computed(() => {
    if (!form.value.chapterUrlFormat || !form.value.testSlug || !form.value.testChapterNumber) {
        return '';
    }
    return form.value.chapterUrlFormat
        .replace('{slug}', form.value.testSlug)
        .replace('{chapterNumber}', form.value.testChapterNumber);
});

watch(() => props.source, (newSource) => {
    if (newSource) {
        form.value = {
            baseUrl: newSource.baseUrl || '',
            imageSelector: newSource.imageSelector || '',
            chapterUrlFormat: newSource.chapterUrlFormat || '',
            nextPageSelector: newSource.nextPageSelector || '',
            chapterSelector: newSource.chapterSelector || '',
            scrapingType: (newSource.scrapingType || 'html').toLowerCase(),
            token: newSource.token || '',
            testSlug: newSource.testSlug || '',
            testChapterNumber: newSource.testChapterNumber ?? '',
        };
    } else {
        form.value = {
            baseUrl: '',
            imageSelector: '',
            chapterUrlFormat: '',
            nextPageSelector: '',
            chapterSelector: '',
            scrapingType: 'html',
            token: '',
            testSlug: '',
            testChapterNumber: '',
        };
    }
}, { immediate: true });

const handleSubmit = () => {
    emit('submit', { ...form.value });
};

defineExpose({ submitForm: handleSubmit });

const testConfiguration = async () => {
    testing.value = true;
    try {
        await emit('test', {
            configuration: { ...form.value },
            testData: {
                mangaSlug: form.value.testSlug,
                chapterNumber: form.value.testChapterNumber,
                testUrl: generatedTestUrl.value,
            }
        });
    } finally {
        testing.value = false;
    }
};
</script>
