<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { apiURL } from '@Services/Api';

/** Props */
const props = defineProps({
    tier: {
        type: Object,
        required: true
    }
});

/** Emits */
const emit = defineEmits(['toggled']);

/** Estado */
const isProcessing = ref(false);

/** Métodos */
const toggleActive = async () => {
    if (isProcessing.value) return;

    isProcessing.value = true;

    try {
        const { data } = await axios({
            method: 'patch',
            url: apiURL(`client-tiers/${props.tier.id}/toggle-active`),
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Authorization': `Bearer ${sessionStorage.token}`
            }
        });

        if (data.status === 'success') {
            window.Notify.success(`Nivel ${props.tier.is_active ? 'desactivado' : 'activado'} exitosamente`);
            emit('toggled');
        } else {
            window.Notify.error(data.message || 'Error al cambiar el estado del nivel');
        }
    } catch (error) {
        console.error('Error toggling tier:', error);
        const message = error.response?.data?.data?.message || error.response?.data?.message || 'Error de conexión al cambiar el estado';
        window.Notify.error(message);
    } finally {
        isProcessing.value = false;
    }
};
</script>

<template>
    <div class="flex justify-center items-center w-full">
        <button
            @click="toggleActive"
            :disabled="isProcessing"
            :class="[
                'relative inline-flex items-center h-7 rounded-full w-20 transition-colors duration-200 focus:outline-none',
                props.tier.is_active ? 'bg-green-500' : 'bg-gray-400',
                isProcessing ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
            ]"
            :title="props.tier.is_active ? 'Click para desactivar' : 'Click para activar'"
        >
            <!-- Texto -->
            <span
                :class="[
                    'absolute text-white font-semibold text-[8px] tracking-wide transition-all duration-200',
                    props.tier.is_active ? 'left-2' : 'right-2'
                ]"
            >
                {{ props.tier.is_active ? 'ACTIVO' : 'INACTIVO' }}
            </span>

            <!-- Círculo deslizable -->
            <span
                :class="[
                    'inline-block h-5 w-5 rounded-full bg-white shadow transition-transform duration-200',
                    props.tier.is_active ? 'translate-x-[54px]' : 'translate-x-1'
                ]"
            ></span>
        </button>
    </div>
</template>
