<script setup>
import { onMounted, ref } from 'vue';
import { useSearcher, useApi, apiURL } from '@Services/Api';
import { can, transl } from './Module';
import { formatCurrency } from '@/utils/formatters';

import SearcherHead from '@Holos/Searcher.vue';
import Table        from '@Holos/Table.vue';
import GoogleIcon   from '@Shared/GoogleIcon.vue';
import CreateModal  from './Create.vue';
import EditModal    from './Edit.vue';
import DeleteModal  from './Delete.vue';

/** Estado */
const bills             = ref([]);
const showCreateModal   = ref(false);
const showEditModal     = ref(false);
const showDeleteModal   = ref(false);
const editingBill       = ref(null);
const deletingBill      = ref(null);

/** Búsqueda */
const searcher = useSearcher({
    url: apiURL('bills'),
    onSuccess: (r) => bills.value = r.bills,
    onError: () => bills.value = []
});

/** Métodos */
const openCreateModal = () => showCreateModal.value = true;
const closeCreateModal = () => showCreateModal.value = false;

const openEditModal = (bill) => {
    editingBill.value = bill;
    showEditModal.value = true;
};
const closeEditModal = () => {
    showEditModal.value = false;
    editingBill.value = null;
};

const openDeleteModal = (bill) => {
    deletingBill.value = bill;
    showDeleteModal.value = true;
};
const closeDeleteModal = () => {
    showDeleteModal.value = false;
    deletingBill.value = null;
};

const confirmDelete = async (id) => {
    try {
        const response = await fetch(apiURL(`bills/${id}`), {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });

        if (response.ok) {
            window.Notify.success('Factura eliminada exitosamente');
            closeDeleteModal();
            searcher.search();
        } else {
            window.Notify.error('Error al eliminar la factura');
        }
    } catch (error) {
        window.Notify.error('Error al eliminar la factura');
    }
};

const onSaved = () => searcher.search();

const api = useApi();

const togglePaid = (bill) => {
    api.patch(apiURL(`bills/${bill.id}/toggle-paid`), {
        onSuccess: () => searcher.refresh(),
    });
};

const exportPending = () => {
    const now = new Date();
    const pad = (n) => String(n).padStart(2, '0');
    const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;
    const time = `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
    api.download(apiURL('bills/pending/excel'), `Facturas_Pendientes_${date}_${time}.xlsx`);
};

/** Ciclo de vida */
onMounted(() => searcher.search());
</script>

<template>
    <div>
        <SearcherHead
            :title="transl('title')"
            :placeholder="transl('search')"
            @search="(x) => searcher.search(x)"
        >
            <button
                class="flex items-center gap-2 px-3 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
                @click="exportPending"
            >
                <GoogleIcon name="download" class="text-xl" />
                {{ transl('export') }}
            </button>
            <button
                v-if="can('create')"
                class="flex items-center gap-2 px-3 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
                @click="openCreateModal"
            >
                <GoogleIcon name="add" class="text-xl" />
                {{ transl('create.title') }}
            </button>
        </SearcherHead>

        <div class="pt-2 w-full">
            <Table
                :items="bills"
                :processing="searcher.processing"
                @send-pagination="(page) => searcher.pagination(page)"
            >
                <template #head>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {{ transl('name') }}
                    </th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {{ transl('supplier') }}
                    </th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {{ transl('cost') }}
                    </th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {{ transl('deadline') }}
                    </th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {{ transl('file') }}
                    </th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {{ transl('paid') }}
                    </th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {{ $t('actions') }}
                    </th>
                </template>

                <template #body="{ items }">
                    <tr
                        v-for="bill in items"
                        :key="bill.id"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                    >
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{{ bill.name }}</p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p v-if="bill.supplier" class="text-sm text-gray-700 dark:text-gray-300">
                                {{ bill.supplier.business_name }}
                            </p>
                            <span v-else class="text-sm text-gray-400">—</span>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                                {{ formatCurrency(bill.cost) }}
                            </p>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <p v-if="bill.deadline" class="text-sm text-gray-700 dark:text-gray-300">
                                {{ bill.deadline }}
                            </p>
                            <span v-else class="text-sm text-gray-400">—</span>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <a
                                v-if="bill.file_url"
                                :href="bill.file_url"
                                target="_blank"
                                class="inline-flex items-center gap-1 text-sm text-indigo-600 hover:text-indigo-800 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                            >
                                <GoogleIcon name="description" class="text-base" />
                                {{ transl('view_file') }}
                            </a>
                            <span v-else class="text-sm text-gray-400">—</span>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <button
                                class="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold transition-colors"
                                :class="bill.paid
                                    ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400'
                                    : 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400'"
                                :title="bill.paid ? transl('toggle_unpaid') : transl('toggle_paid')"
                                @click.stop="togglePaid(bill)"
                            >
                                <GoogleIcon :name="bill.paid ? 'check_circle' : 'schedule'" class="text-base" />
                                {{ bill.paid ? transl('paid') : transl('pending') }}
                            </button>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="flex items-center justify-center gap-2">
                                <button
                                    v-if="can('edit')"
                                    class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                                    :title="$t('crud.edit')"
                                    @click.stop="openEditModal(bill)"
                                >
                                    <GoogleIcon name="edit" class="text-xl" />
                                </button>
                                <button
                                    v-if="can('destroy')"
                                    class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                                    :title="$t('crud.destroy')"
                                    @click.stop="openDeleteModal(bill)"
                                >
                                    <GoogleIcon name="delete" class="text-xl" />
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>

                <template #empty>
                    <td colspan="7" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-8 text-gray-500">
                            <GoogleIcon name="receipt_long" class="text-6xl mb-2 opacity-50" />
                            <p class="font-semibold">{{ $t('registers.empty') }}</p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>

        <CreateModal
            v-if="can('create')"
            :show="showCreateModal"
            @close="closeCreateModal"
            @created="onSaved"
        />

        <EditModal
            v-if="can('edit')"
            :show="showEditModal"
            :bill="editingBill"
            @close="closeEditModal"
            @updated="onSaved"
        />

        <DeleteModal
            v-if="can('destroy')"
            :show="showDeleteModal"
            :bill="deletingBill"
            @close="closeDeleteModal"
            @confirm="confirmDelete"
        />
    </div>
</template>
