<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head, useForm, Link } from '@inertiajs/vue3';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import InputError from '@/Components/InputError.vue';
import InputLabel from '@/Components/InputLabel.vue';
import TextInput from '@/Components/TextInput.vue';

const props = defineProps({
    template: Object,
    services: Array,
});

const form = useForm({
    name: props.template.name,
    description: props.template.description,
    is_active: Boolean(props.template.is_active),
    items: props.template.service_items.map(item => ({
        service_id: item.service_id,
        label: item.label,
        is_mandatory: Boolean(item.is_mandatory),
        fields: item.fields || [],
    })),
});

const addItem = () => {
    form.items.push({
        service_id: props.services.length > 0 ? props.services[0].id : '',
        label: '',
        is_mandatory: false,
        fields: [],
    });
};

const removeItem = (index) => {
    form.items.splice(index, 1);
};

const addField = (item) => {
    if (!item.fields) item.fields = [];
    item.fields.push({
        label: '',
        type: 'text',
        required: false,
    });
};

const removeField = (item, index) => {
    item.fields.splice(index, 1);
};

const submit = () => {
    form.put(route('templates.update', props.template.id));
};
</script>

<template>
    <Head title="Modifier Modèle" />

    <AuthenticatedLayout>
        <template #header>
            <h2 class="text-xl font-semibold leading-tight text-gray-800 dark:text-gray-200">
                Modifier Modèle: {{ template.name }}
            </h2>
        </template>

        <div class="py-12">
            <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg dark:bg-gray-800 p-6">
                    <form @submit.prevent="submit" class="space-y-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <InputLabel for="name" value="Nom du modèle" />
                                <TextInput id="name" type="text" class="mt-1 block w-full" v-model="form.name" required autofocus />
                                <InputError class="mt-2" :message="form.errors.name" />
                            </div>

                            <div>
                                <InputLabel for="description" value="Description" />
                                <TextInput id="description" type="text" class="mt-1 block w-full" v-model="form.description" />
                                <InputError class="mt-2" :message="form.errors.description" />
                            </div>
                        </div>

                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" v-model="form.is_active" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500 dark:border-gray-700 dark:bg-gray-900 dark:focus:ring-indigo-600 dark:focus:ring-offset-gray-800">
                                <span class="ml-2 text-sm text-gray-600 dark:text-gray-400">Modèle Actif</span>
                            </label>
                        </div>

                        <div class="border-t border-gray-200 dark:border-gray-700 pt-6">
                            <div class="flex justify-between items-center mb-4">
                                <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">Tâches par Service</h3>
                                <button type="button" @click="addItem" class="text-sm bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 px-3 py-1 rounded">
                                    + Ajouter une tâche
                                </button>
                            </div>

                            <div v-if="form.items.length === 0" class="text-center text-gray-500 italic py-4">
                                Aucune tâche définie. Ajoutez des tâches pour ce modèle.
                            </div>

                            <div v-else class="space-y-4">
                                <div v-for="(item, index) in form.items" :key="index" class="p-4 bg-gray-50 dark:bg-gray-700/30 rounded-lg space-y-4">
                                    <div class="flex items-start space-x-4">
                                        <div class="w-1/4">
                                            <InputLabel value="Service" class="mb-1" />
                                            <select v-model="item.service_id" class="block w-full border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 focus:border-indigo-500 dark:focus:border-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-600 rounded-md shadow-sm text-sm">
                                                <option v-for="service in services" :key="service.id" :value="service.id">
                                                    {{ service.name }}
                                                </option>
                                            </select>
                                        </div>
                                        <div class="flex-1">
                                            <InputLabel value="Libellé de la tâche" class="mb-1" />
                                            <TextInput type="text" class="block w-full" v-model="item.label" required placeholder="Ex: Créer compte AD" />
                                        </div>
                                        <div class="pt-6">
                                            <label class="flex items-center">
                                                <input type="checkbox" v-model="item.is_mandatory" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500 dark:border-gray-700 dark:bg-gray-900 dark:focus:ring-indigo-600 dark:focus:ring-offset-gray-800">
                                                <span class="ml-2 text-sm text-gray-600 dark:text-gray-400">Obligatoire</span>
                                            </label>
                                        </div>
                                        <div class="pt-6">
                                            <button type="button" @click="removeItem(index)" class="text-red-500 hover:text-red-700">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                                    <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                                                </svg>
                                            </button>
                                        </div>
                                    </div>
                                    
                                    <!-- Custom Fields -->
                                    <div class="pl-4 border-l-2 border-indigo-200 dark:border-indigo-800 ml-4 space-y-2">
                                        <div class="flex items-center justify-between">
                                             <h4 class="text-xs font-semibold uppercase text-gray-500 dark:text-gray-400">Données à saisir par le service</h4>
                                             <button type="button" @click="addField(item)" class="text-xs text-indigo-600 hover:text-indigo-800 dark:text-indigo-400 dark:hover:text-indigo-300 font-medium">
                                                 + Ajouter un champ
                                             </button>
                                        </div>
                                        
                                        <div v-for="(field, fIndex) in item.fields" :key="fIndex" class="flex items-center space-x-2 bg-white dark:bg-gray-800 p-2 rounded shadow-sm border border-gray-200 dark:border-gray-700">
                                             <TextInput v-model="field.label" placeholder="Nom du champ (ex: Login)" class="text-xs w-1/3 py-1" />
                                             <select v-model="field.type" class="text-xs rounded-md border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 focus:border-indigo-500 focus:ring-indigo-500 py-1">
                                                <option value="text">Texte</option>
                                                <option value="checkbox">Case à cocher</option>
                                                <option value="date">Date</option>
                                             </select>
                                             <label class="flex items-center ml-2">
                                                <input type="checkbox" v-model="field.required" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500 dark:border-gray-700 dark:bg-gray-900 dark:focus:ring-indigo-600 dark:focus:ring-offset-gray-800 h-3 w-3">
                                                <span class="ml-1 text-xs text-gray-600 dark:text-gray-400">Requis</span>
                                             </label>
                                             <button type="button" @click="removeField(item, fIndex)" class="text-red-500 hover:text-red-700 ml-auto p-1">
                                                 x
                                             </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <InputError class="mt-2" :message="form.errors.items" />
                        </div>

                        <div class="flex items-center gap-4">
                            <PrimaryButton :disabled="form.processing">Mettre à jour</PrimaryButton>
                            <Link :href="route('templates.index')" class="text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 underline">Annuler</Link>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>
