<template>
    <div class="row">
        <div class="col">
            <loading-component style="height: 200px; top: 0;" key="1" color="success" v-show="isLoading" />
            <div v-if="!isLoading">
                <div class="row">
                    <div class="col-8">
                        <div class="row p-b-5 b-b b-grey m-b-10 m-l-0 m-r-0">
                            <div class="col no-padding">
                                <h6>Wallet Transaction History</h6>
                            </div>
                        </div>
                        <div class="row m-t-10 m-b-10">
                            <div class="col">
                                <div class="d-flex align-items-center h-100">
                                    <span class="btn btn-md fs-11 bg-primary text-white fs-12 m-r-5" :class="[{'bg-primary-darker': showingPreciseAmount}]" @click="showingPreciseAmount = !showingPreciseAmount">{{ showingPreciseAmount ? 'Showing Precise Wallet Transaction' : 'Show Precise Wallet Transaction'}}</span>
                                    <a v-if="company" @click="download(company, showingPreciseAmount)" target="_blank" class="btn btn-md btn-primary fs-12"><i class="fa fa-download m-r-5"></i>{{ showingPreciseAmount ? 'Download Precise Transaction' : 'Download Transaction'}}</a>
                                </div>
                            </div>
                            <div class="col-2">
                                <validation-wrapper-component selectable :validator="v$.showingTransactionCount">
                                    <label>Showing Rows</label>
                                    <select-component :options="transactionCountOptions" v-model="showingTransactionCount" />
                                </validation-wrapper-component>
                            </div>
                        </div>
                        <div v-if="!showingPreciseAmount">
                            <customer-transaction-component :decimals="2" :wallet_id="wallet_id" :showingTransactionCount="showingTransactionCount" />
                        </div>
                        <div v-if="showingPreciseAmount">
                            <customer-transaction-component :decimals="5" :wallet_id="wallet_id" :showingTransactionCount="showingTransactionCount" />
                        </div>
                    </div>
                    <div class="col-3 m-l-15">
                        <wallet-component :data="company" :creditable="true" />
                        <div class="row m-t-20">
                            <div class="col">
                                <div class="row m-b-10">
                                    <div class="col">
                                        <div class="font-head fs-10 all-caps">Top Up Records</div>
                                    </div>
                                </div>
                                <div class="row" v-if="company?.wallet">
                                    <div class="col">
                                        <wallet-top-up-history-component v-for="item in company.wallet.top_up_records" :key="item.id" :data="item" />
                                    </div>
                                </div>
                                <div class="row align-items-center justify-content-center p-t-50 p-b-50" v-if="!company?.wallet || !company.wallet.top_up_records.length">
                                    <div class="col-10">
                                        <div class="row align-items-center justify-content-center hint-text">
                                            <div class="col-4 hint-text"><img :src="asset('images/not-found-illustration.png')" class="w-100 hint-text"></div>
                                        </div>
                                        <div class="row text-center">
                                            <div class="col">
                                                <div class="row m-t-20">
                                                    <div class="col">
                                                        <p class="all-caps no-margin fs-11" style="letter-spacing: 2px;">Nothing To Show Here</p>
                                                    </div>
                                                </div>
                                                <div class="row m-t-5 align-items-center justify-content-center">
                                                    <div class="col">
                                                        <small class="fs-9 muted all-caps font-lato" style="letter-spacing: 2px">There is no results found, Try adjusting your filters to find what you are looking for.</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useFormHandler } from '@/composables/useFormHandler';
import { useQueueStore } from '@/stores/queue';
import { useCrudStore } from '@/stores/crud';
import { useVuelidate } from '@vuelidate/core';
import route from '@/general/functions/router';

interface Props {
    id: number;
    wallet_id: number;
}

const props = defineProps<Props>();

const section = 'customerTransactionSection';
const company = ref<any>(null);
const showingPreciseAmount = ref(false);
const showingTransactionCount = ref(10);
const transactionCountOptions = [5, 10, 20, 30, 50];

const queueStore = useQueueStore();
const crudStore = useCrudStore();

const { submit, isLoading } = useFormHandler({
    section: section
});

const rules = {
    showingTransactionCount: {}
};

const v$ = useVuelidate(rules, { showingTransactionCount });

const fetchCompany = () => {
    submit(route('api.company.show', props.id), 'get', section, false, false, null, {
        successHandler: (response: any) => {
            company.value = response.payload.data;
        }
    });
};

watch(() => queueStore.isInCompleteQueue(section), (inComplete) => {
    if (inComplete) {
        fetchCompany();
    }
});

onMounted(() => {
    queueStore.updateListQueue({ name: section });
});

const asset = (path: string) => (window as any).Vapor.asset(path);

const download = async (targetCompany: any, paramShowingPreciseAmount: boolean) => {
    const url = route('wallet.details-export', targetCompany.reference, paramShowingPreciseAmount);
    const vaporEnabled = window.LARAVEL_VAPOR_ENABLED;

    if (vaporEnabled) {
        try {
            const response: any = await crudStore.crudRequest({ endpoint: url, method: 'get' });
            if (response && response.ok) {
                const result = await response.json();
                if (result.src) {
                    window.open(result.src, '_blank');
                }
            }
        } catch (error) {
            console.error('Download error:', error);
        }
    } else {
        window.open(url, '_blank');
    }
};
</script>
