<script setup>
import { ref, watch } from 'vue';
import { api, apiURL } from '@Services/Api';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import Modal from '@Holos/Modal.vue';

/** Props */
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    saleData: {
        type: Object,
        default: null
    }
});

const usoCfdiOptions = [
    { value: 'G01', label: 'G01 - Adquisición de mercancías' },
    { value: 'G02', label: 'G02 - Devoluciones, descuentos o bonificaciones' },
    { value: 'G03', label: 'G03 - Gastos en general' },
    { value: 'I01', label: 'I01 - Construcciones' },
    { value: 'I02', label: 'I02 - Mobiliario y equipo de oficina por inversiones' },
    { value: 'I03', label: 'I03 - Equipo de transporte' },
    { value: 'I04', label: 'I04 - Equipo de computo y accesorios' },
    { value: 'I05', label: 'I05 - Dados, troqueles, moldes, matrices y herramental' },
    { value: 'I06', label: 'I06 - Comunicaciones telefónicas' },
    { value: 'I07', label: 'I07 - Comunicaciones satelitales' },
    { value: 'I08', label: 'I08 - Otra maquinaria y equipo' },
    { value: 'S01', label: 'S01 - Sin efectos fiscales' }
];

const regimenFiscalOptions = [
    { value: '601', label: '601 - General de Ley Personas Morales' },
    { value: '603', label: '603 - Personas Morales con Fines no Lucrativos' },
    { value: '610', label: '610 - Residentes en el Extranjero sin Establecimiento Permanentes en México' },
    { value: '620', label: '620 - Sociedades Cooperativas de Producción que optan por diferir sus ingresos' },
    { value: '622', label: '622 - Actividades Agrícolas, Ganaderas, Silvícolas y Pesqueras' },
    { value: '623', label: '623 - Opcional para Grupos de Sociedades' },
    { value: '624', label: '624 - Coordinados' },
    { value: '626', label: '626 - Régimen Simplificado de Confianza' }
];

/** Emits */
const emit = defineEmits(['close', 'save']);

/** Estado */
const form = ref({
    name: '',
    email: '',
    phone: '',
    address: '',
    rfc: '',
    razon_social: '',
    regimen_fiscal: '',
    cp_fiscal: '',
    uso_cfdi: ''
});
const saving = ref(false);

/** Watchers */
// Resetear formulario cuando se abre el modal
watch(() => props.show, (isShown) => {
    if (isShown) {
        form.value = {
            name: '',
            email: '',
            phone: '',
            address: '',
            rfc: '',
            razon_social: '',
            regimen_fiscal: '',
            cp_fiscal: '',
            uso_cfdi: ''
        };
    }
});

/** Métodos */
const handleSave = async () => {
    // Validar que al menos el nombre esté presente
    if (!form.value.name || form.value.name.trim() === '') {
        window.Notify.error('El nombre del cliente es requerido');
        return;
    }

    saving.value = true;

    api.post(apiURL('clients'), {
        data: form.value,
        onSuccess: (response) => {
            saving.value = false;
            window.Notify.success('Cliente guardado correctamente');
            emit('save', response.client);
            handleClose();
        },
        onFail: (failData) => {
            saving.value = false;
            window.Notify.error(failData?.message || 'Error al guardar el cliente');
        },
        onError: (error) => {
            saving.value = false;
            window.Notify.error(error?.message || 'Error en la solicitud al guardar el cliente');
        }
    });
};

const handleClose = () => {
    if (!saving.value) {
        form.value = {
            name: '',
            email: '',
            phone: '',
            address: '',
            rfc: '',
            razon_social: '',
            regimen_fiscal: '',
            cp_fiscal: '',
            uso_cfdi: ''
        };
        emit('close');
    }
};
</script>

<template>
    <Modal :show="show" max-width="lg" @close="handleClose">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center gap-3">
                    <div class="flex items-center justify-center w-14 h-14 rounded-full bg-blue-100 dark:bg-blue-900/30">
                        <GoogleIcon name="person_add" class="text-3xl text-blue-600 dark:text-blue-400" />
                    </div>
                    <div>
                        <h3 class="text-xl font-bold text-gray-900 dark:text-gray-100">
                            Registrar Cliente
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            ¿Deseas guardar los datos del cliente? (Opcional)
                        </p>
                    </div>
                </div>
                <button
                    @click="handleClose"
                    :disabled="saving"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors disabled:opacity-50"
                >
                    <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>

            <!-- Información de venta (opcional) -->
            <div v-if="saleData" class="mb-6 p-4 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg">
                <div class="flex items-center gap-2 mb-2">
                    <GoogleIcon name="receipt_long" class="text-lg text-gray-600 dark:text-gray-400" />
                    <span class="text-sm font-semibold text-gray-700 dark:text-gray-300">Venta realizada</span>
                </div>
                <p class="text-xs text-gray-500 dark:text-gray-400">
                    Total: <span class="font-bold">${{ saleData.total?.toFixed(2) || '0.00' }}</span>
                </p>
            </div>

            <!-- Formulario -->
            <form @submit.prevent="handleSave" class="space-y-4">
                <!-- Nombre (Requerido) -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        Nombre Completo *
                    </label>
                    <div class="relative">
                        <input
                            v-model="form.name"
                            type="text"
                            placeholder="Nombre del cliente"
                            maxlength="255"
                            required
                            class="w-full px-4 py-3 pl-11 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400"
                            :disabled="saving"
                        />
                        <GoogleIcon name="person" class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xl" />
                    </div>
                </div>

                <!-- Email -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        Correo Electrónico
                    </label>
                    <div class="relative">
                        <input
                            v-model="form.email"
                            type="email"
                            placeholder="correo@ejemplo.com"
                            maxlength="255"
                            class="w-full px-4 py-3 pl-11 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400"
                            :disabled="saving"
                        />
                        <GoogleIcon name="email" class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xl" />
                    </div>
                </div>

                <!-- Teléfono -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        Teléfono
                    </label>
                    <div class="relative">
                        <input
                            v-model="form.phone"
                            type="tel"
                            placeholder="(123) 456-7890"
                            maxlength="20"
                            class="w-full px-4 py-3 pl-11 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400"
                            :disabled="saving"
                        />
                        <GoogleIcon name="phone" class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xl" />
                    </div>
                </div>

                <!-- RFC -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        RFC
                    </label>
                    <div class="relative">
                        <input
                            v-model="form.rfc"
                            type="text"
                            placeholder="XAXX010101000"
                            maxlength="13"
                            class="w-full px-4 py-3 pl-11 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 uppercase"
                            :disabled="saving"
                        />
                        <GoogleIcon name="badge" class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xl" />
                    </div>
                </div>

                <!-- Razón Social-->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        Razón Social
                    </label>
                    <div class="relative">
                        <input
                            v-model="form.razon_social"
                            type="text"
                            placeholder="Razón social"
                            maxlength="13"
                            class="w-full px-4 py-3 pl-11 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400"
                            :disabled="saving"
                        />
                        <GoogleIcon name="badge" class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xl" />
                    </div>
                </div>
                
                <!-- Uso CFDI Select -->
                <div>
                    <label for="uso_cfdi" class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                        Uso de CFDI
                    </label>
                    <select
                        v-model="form.uso_cfdi"
                        id="uso_cfdi"
                        class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100"
                        :disabled="saving"
                    >
                        <option value="">Seleccionar uso de CFDI</option>
                        <option
                            v-for="option in usoCfdiOptions"
                            :key="option.value"
                            :value="option.value"
                        >
                            {{ option.label }}
                        </option>
                    </select>
                </div>

                <!-- Régimen Fiscal Select -->
                <div>
                    <label for="regimen_fiscal" class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                        Régimen Fiscal
                    </label>
                    <select
                        v-model="form.regimen_fiscal"
                        id="regimen_fiscal"
                        class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100"
                        :disabled="saving"
                    >
                        <option value="">Seleccionar régimen fiscal</option>
                        <option
                            v-for="option in regimenFiscalOptions"
                            :key="option.value"
                            :value="option.value"
                        >
                            {{ option.label }}
                        </option>
                    </select>
                </div>

                <!-- Dirección -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        Dirección
                    </label>
                    <div class="relative">
                        <textarea
                            v-model="form.address"
                            placeholder="Calle, número, colonia, ciudad"
                            maxlength="500"
                            rows="3"
                            class="w-full px-4 py-3 pl-11 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 resize-none"
                            :disabled="saving"
                        ></textarea>
                        <GoogleIcon name="location_on" class="absolute left-3 top-4 text-gray-400 text-xl" />
                    </div>
                </div>
            </form>

            <!-- Footer -->
            <div class="flex items-center justify-end gap-3 mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
                <button
                    type="button"
                    @click="handleClose"
                    :disabled="saving"
                    class="px-6 py-2.5 text-sm font-semibold text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    Cancelar
                </button>
                <button
                    type="button"
                    @click="handleSave"
                    :disabled="saving || !form.name"
                    class="flex items-center gap-2 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-lg focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-600 shadow-lg shadow-blue-600/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:shadow-none"
                >
                    <GoogleIcon
                        :name="saving ? 'hourglass_empty' : 'save'"
                        class="text-xl"
                        :class="{ 'animate-spin': saving }"
                    />
                    <span v-if="saving">Guardando...</span>
                    <span v-else>Guardar Cliente</span>
                </button>
            </div>
        </div>
    </Modal>
</template>
