<script setup>
import { onMounted, ref } from 'vue';
import { useForm, useApi, apiURL } from '@Services/Api';
import { transl } from './Module';

import Modal           from '@Holos/Modal.vue';
import FormInput       from '@Holos/Form/Input.vue';
import FormError       from '@Holos/Form/Elements/Error.vue';
import SingleFile      from '@Holos/Form/SingleFile.vue';
import Selectable      from '@Holos/Form/Selectable.vue';
import GoogleIcon      from '@Shared/GoogleIcon.vue';
import SupplierCreate  from '@Pages/POS/Suppliers/Create.vue';

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

/** Propiedades */
defineProps({
    show: Boolean
});

/** Estado */
const api = useApi();
const suppliers = ref([]);
const selectedSupplier = ref(null);
const showSupplierModal = ref(false);

/** Formulario */
const form = useForm({
    name: '',
    cost: '',
    deadline: '',
    supplier_id: null,
    paid: false,
    file: null,
});

/** Métodos */
const create = () => {
    form.supplier_id = selectedSupplier.value?.id ?? null;
    form.post(apiURL('bills'), {
        onSuccess: (data) => {
            window.Notify.success(Lang('register.create.onSuccess'));
            emit('created', data.bill);
            closeModal();
        },
    });
};

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

const loadSuppliers = () => {
    api.get(apiURL('proveedores'), {
        onSuccess: (data) => suppliers.value = data.suppliers?.data ?? [],
    });
};

/** Ciclo de vida */
onMounted(loadSuppliers);
</script>

<template>
    <Modal :show="show" max-width="lg" @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">
                    {{ transl('create.title') }}
                </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="create" class="space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <!-- Proveedor -->
                    <div class="col-span-2">
                        <div class="flex items-center justify-between mb-1.5">
                            <label class="text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase">
                                {{ transl('supplier') }}
                            </label>
                            <button
                                type="button"
                                class="flex items-center justify-center w-6 h-6 rounded-full bg-indigo-600 hover:bg-indigo-700 text-white transition-colors"
                                :title="$t('crud.create')"
                                @click="showSupplierModal = true"
                            >
                                <GoogleIcon name="add" class="text-sm" />
                            </button>
                        </div>
                        <Selectable
                            v-model="selectedSupplier"
                            :options="suppliers"
                            label="business_name"
                            track-by="id"
                            :placeholder="transl('supplier')"
                        />
                        <FormError :message="form.errors?.supplier_id" />
                    </div>

                    <!-- Nombre -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            {{ transl('name') }}
                        </label>
                        <FormInput
                            v-model="form.name"
                            type="text"
                            :placeholder="transl('name')"
                            autofocus
                            required
                        />
                        <FormError :message="form.errors?.name" />
                    </div>

                    <!-- Costo -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            {{ transl('cost') }}
                        </label>
                        <FormInput
                            v-model="form.cost"
                            type="number"
                            step="0.01"
                            min="0"
                            :placeholder="transl('cost')"
                            required
                        />
                        <FormError :message="form.errors?.cost" />
                    </div>

                    <!-- Fecha límite -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            {{ transl('deadline') }}
                        </label>
                        <FormInput
                            v-model="form.deadline"
                            type="date"
                        />
                        <FormError :message="form.errors?.deadline" />
                    </div>

                    <!-- Pagada -->
                    <div class="col-span-2 flex items-center gap-3">
                        <input
                            id="create-paid"
                            v-model="form.paid"
                            type="checkbox"
                            class="w-4 h-4 text-indigo-600 rounded border-gray-300 focus:ring-indigo-500"
                        />
                        <label for="create-paid" class="text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer">
                            {{ transl('paid') }}
                        </label>
                    </div>

                    <!-- Archivo -->
                    <div class="col-span-2">
                        <SingleFile
                            v-model="form.file"
                            accept="application/pdf,image/jpeg,image/png,image/jpg"
                            title="bills.file"
                        />
                        <FormError :message="form.errors?.file" />
                    </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"
                    >
                        {{ $t('cancel') }}
                    </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">{{ $t('saving') }}...</span>
                        <span v-else>{{ $t('save') }}</span>
                    </button>
                </div>
            </form>
        </div>
    </Modal>

    <SupplierCreate
        :show="showSupplierModal"
        @close="showSupplierModal = false"
        @created="() => { showSupplierModal = false; loadSuppliers(); }"
    />
</template>
