<script setup>
import { watch } from 'vue';
import { useForm, apiURL } from '@Services/Api';

import Modal from '@Holos/Modal.vue';
import FormInput from '@Holos/Form/Input.vue';
import FormError from '@Holos/Form/Elements/Error.vue';

/** Eventos */
const emit = defineEmits(['close', 'updated']);

/** Propiedades */
const props = defineProps({
    show: Boolean,
    client: Object
});

/** Formulario */
const form = useForm({
    tier_name: '',
    min_purchase_amount: '',
    max_purchase_amount: '',
    discount_percentage: '',
    is_active: true,
});

/** Métodos */
const updateTier = () => {
    form.put(apiURL(`client-tiers/${props.client.id}`), {
        onSuccess: () => {
            window.Notify.success('Nivel de cliente actualizado exitosamente');
            emit('updated');
            closeModal();
        },
        onError: () => {
            window.Notify.error('Error al actualizar el nivel de cliente');
        }
    });
};

const closeModal = () => {
    form.reset();
    emit('close');
};

/** Observadores */
watch(() => props.client, (newTier) => {
    if (newTier) {
        form.tier_name = newTier.tier_name || '';
        form.min_purchase_amount = newTier.min_purchase_amount || '';
        form.max_purchase_amount = newTier.max_purchase_amount || '';
        form.discount_percentage = newTier.discount_percentage || '';
        form.is_active = newTier.is_active ?? true;
    }
}, { immediate: true });
</script>

<template>
    <Modal :show="show" max-width="md" @close="closeModal">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                    Editar Nivel de Cliente
                </h3>
                <button
                    @click="closeModal"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                    <svg class="w-5 h-5" 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>
            </div>

            <!-- Formulario -->
            <form @submit.prevent="updateTier" class="space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <!-- Nombre -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NOMBRE
                        </label>
                        <FormInput
                            v-model="form.tier_name"
                            type="text"
                            placeholder="Nombre del nivel"
                            required
                        />
                        <FormError :message="form.errors?.tier_name" />
                    </div>

                    <!-- Monto Mínimo-->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            MONTO MÍNIMO ACUMULADO
                        </label>
                        <FormInput
                            v-model="form.min_purchase_amount"
                            type="number"
                            step="0.01"
                            min="0"
                            placeholder="0.00"
                            required
                        />
                        <FormError :message="form.errors?.min_purchase_amount" />
                    </div>
                    <!-- Monto Máximo-->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            MONTO MÁXIMO ACUMULADO <span class="text-gray-400 text-xs normal-case">(opcional)</span>
                        </label>
                        <FormInput
                            v-model="form.max_purchase_amount"
                            type="number"
                            step="0.01"
                            min="0"
                            placeholder="Sin límite"
                        />
                        <FormError :message="form.errors?.max_purchase_amount" />
                    </div>

                    <!-- Descuento -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            DESCUENTO (%)
                        </label>
                        <FormInput
                            v-model="form.discount_percentage"
                            type="number"
                            step="0.01"
                            min="0"
                            max="100"
                            placeholder="0.00"
                            required
                        />
                        <FormError :message="form.errors?.discount_percentage" />
                    </div>

                    <!-- Estado -->
                    <div class="col-span-2">
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input
                                v-model="form.is_active"
                                type="checkbox"
                                class="w-4 h-4 text-indigo-600 bg-gray-100 border-gray-300 rounded focus:ring-indigo-500 dark:focus:ring-indigo-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                            />
                            <span class="text-sm font-medium text-gray-700 dark:text-gray-300">
                                Nivel activo
                            </span>
                        </label>
                        <FormError :message="form.errors?.is_active" />
                    </div>
                </div>

                <!-- Botones -->
                <div class="flex items-center justify-end gap-3 mt-6">
                    <button
                        type="button"
                        @click="closeModal"
                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                    >
                        Cancelar
                    </button>
                    <button
                        type="submit"
                        :disabled="form.processing"
                        class="px-4 py-2 text-sm font-semibold text-white bg-gray-900 rounded-lg hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                        <span v-if="form.processing">Actualizando...</span>
                        <span v-else>Actualizar</span>
                    </button>
                </div>
            </form>
        </div>
    </Modal>
</template>
