<script setup>
import { computed, h } from 'vue';
import axios from 'axios';
import { useNavigate } from '../../../composables/Core/useNavigate.js';
import { useAuth } from '../../../composables/Core/useAuth.js';
import { useModal } from '../../../composables/Core/useModal.js';
import ServiceButtonGrid from '../../../Components/Core/Services/ServiceButtonGrid.vue';
import SideTextButtonList from '../../../Components/Core/Services/SideTextButtonList.vue';

const props = defineProps({
    title: { type: String, default: 'Dashboard' }
});

const { UserTypes, role } = useAuth();
const { navigate } = useNavigate();
const modal = useModal();

const services = computed(() => [
    { icon: 'https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/04d0e432a298.bin', title: 'Market', pagename: 'ListProductsMarket' },
    { icon: 'https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/9908be28dd8a.bin', title: 'My Wallet', pagename: 'MyWallet' },
    { icon: 'https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/4d9cb130fad1.bin', title: 'Shipments', pagename: 'ShipmentList' },
]);

const quickActionsItems = computed(() => {
    const items = [
        {
            text: 'Open POS',
            action: 'openPos',
            icon: 'https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/5b5ef88c0ad1.svg',
            roles: [UserTypes.STORE_MANAGER],
        },
        {
            text: 'Onboard New User',
            pagename: 'CreateUser',
            icon: 'https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/516ed2aaaa4c.bin',
            roles: [
                UserTypes.ULTIMATE,
                UserTypes.SUPER_OPERATOR,
                UserTypes.OPERATOR,
                UserTypes.COORDINATOR,
                UserTypes.STORE_OWNER,
                UserTypes.STORE_MANAGER,
                UserTypes.SUPPLIER_OVERSEER,
                UserTypes.SUPPLIER
            ]
        },
        { text: 'My Personal Profile', pagename: 'UserInfoEdit', icon: 'https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/ac7a1cebe580.bin' },
    ];

    return items.filter(item => {
        if (!item.roles) return true;
        return item.roles.includes(role.value);
    });
});

const showStoreSelectModal = (stores) => {
    modal.open({
        title: 'Select a Store',
        body: h('div', { class: 'd-flex flex-column gap-2' },
            stores.map(store =>
                h('button', {
                    class: 'btn btn-outline-primary rounded-pill text-start',
                    onClick: () => {
                        modal.hideModal();
                        navigate({ page: 'PosMain', props: { target: store.hashkey } });
                    },
                }, [
                    h('i', { class: 'fas fa-store me-2' }),
                    store.name,
                    store.category ? h('small', { class: 'text-muted ms-2' }, `(${store.category})`) : null,
                ])
            )
        ),
    });
};

const openPos = async () => {
    try {
        const { data: stores } = await axios.post('/ListStores/MyStores/data', {});
        if (!stores || stores.length === 0) {
            modal.quickDismiss({ title: 'No Store Found', body: 'You have no active stores assigned to your account.' });
            return;
        }
        if (stores.length === 1) {
            navigate({ page: 'PosMain', props: { target: stores[0].hashkey } });
            return;
        }
        showStoreSelectModal(stores);
    } catch (e) {
        modal.quickDismiss({ title: 'Error', body: 'Could not load your stores. Please try again.' });
    }
};

const handleItemClick = async (item) => {
    if (item?.action === 'openPos') {
        await openPos();
        return;
    }
    if (item.pagename) {
        navigate({ page: item.pagename });
    }
};
</script>

<template>
    <div class="home-fragment pb-5">
        <div class="tf-container mt-4">
            <h5 class="fw_7 mb-3">{{ title }} Dashboard</h5>
            <ServiceButtonGrid :items="services" @item-click="handleItemClick" />
        </div>

        <div class="tf-container mt-4">
            <h5 class="fw_7 mb-3">Quick Actions</h5>
            <SideTextButtonList :items="quickActionsItems" @item-click="handleItemClick" />
        </div>
    </div>
</template>
