<template>
    <div class="row">
        <div class="col">
            <div class="row">
                <div class="col-12 col-md">
                    <choose-currency-component v-on:input="updateCurrencyId($event)"></choose-currency-component>
                </div>
                <div class="col-12 col-md">
                    <choose-service-component v-on:input="updateServiceId($event)" v-on:loaded="isLoading=!isLoading"></choose-service-component>
                </div>
                <div class="col-12 col-md">
                    <validation-wrapper-component :validator="$v.filters.date_from">
                        <label class="all-caps">Date From</label>
                        <date-picker-component v-model.lazy="filters.date_from"></date-picker-component>
                    </validation-wrapper-component>
                </div>
                <div class="col-12  col-md">
                    <validation-wrapper-component :validator="$v.filters.date_to">
                        <label class="all-caps">Date To</label>
                        <date-picker-component v-model.lazy="filters.date_to"></date-picker-component>
                    </validation-wrapper-component>
                </div>
            </div>
            <div class="row m-t-15">
                <div class="col">
                    <button type="button" class="btn btn-lg btn-primary fs-11 " @click="fetchRateLogs" :class="[{'disabled': isLoading}]" :disabled="isLoading">Search</button>
                    <!-- <button type="button" class="btn btn-lg btn-secondary fs-11" @click="resetSarch">Reset</button> -->
                </div>
            </div>
            <loading-component style="height: 200px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>           
            <div class="row" v-if="!isLoading && !hasError">
                <div class="col-12 mx-auto p-0 ">
                    <canvas style="width: 800px; height:350px" id="currency-history-chart"></canvas>
                </div>
            </div>
            <div class="row" v-if="hasError">
                <div class="col">
                    <div class="row align-items-center justify-content-center  hint-text">
                        <div class="col-4 hint-text"><img src="/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>
</template>

<script>
import Chart from 'chart.js';

export default {
    data() {
        return {
            rateHistory: null,
            isLoading: true,
            hasError: false,
            section: 'rateHistorySection',
            minWidth: {
                minWidth: "100px",
            },
            minWidth150: {
                minWidth: "150px",
            },
            filters: {
                currency_id: null,
                service_id: null,
                date_to: null,
                date_from: null,
            },
            chartLebels:[],
            chartData: [],
            paymentMethodsConst: [],
            colors: [
                'red',
                'pink',
                'blue',
                'purple',
                'black',
                'yellow'
            ]
        };
    },
    props:{
        paymentMethods: {
            type: Object
        }
    },
    computed: {
        pendingQueue() {
            return this.$store.getters.isInCompleteQueue(this.section);
        }
    },
    mounted(){
        this.paymentMethodsConst = Object.entries(this.paymentMethods).reduce((acc, [key, value]) => {
        acc[value] = key;
        return acc;
        }, {});
    },
    watch: {
        pendingQueue(inComplete) {
            if (inComplete) {
                this.resetSarch();
            }
        },
        rateHistory: function(newVal) {

            const date_from_parts = this.filters.date_from.split("-");
            const date_from_year = date_from_parts[2];
            const date_from_month = date_from_parts[1] - 1; // Subtract 1 from month, since it's zero-based in Date objects
            const date_from_day = date_from_parts[0];
            const start = new Date(date_from_year, date_from_month, date_from_day);

            const date_to_parts = this.filters.date_to.split("-");
            const date_to_year = date_to_parts[2];
            const date_to_month = date_to_parts[1] - 1; // Subtract 1 from month, since it's zero-based in Date objects
            const date_to_day = date_to_parts[0];
            const end = new Date(date_to_year, date_to_month, date_to_day);

            // Group rates by payment method type
            const ratesByType = {};
            newVal.forEach(rate => {
            if (!ratesByType[rate.payment_method_type]) {
                ratesByType[rate.payment_method_type] = [];
            }
                ratesByType[rate.payment_method_type].push(rate);
            });

            const startYear = start.getFullYear();
            const startMonth = start.getMonth() + 1;
            const endYear = end.getFullYear();
            const endMonth = end.getMonth() + 1;

            // Get rates for date range
            const ratesForRange = {};
            Object.keys(ratesByType).forEach(type => {
            ratesForRange[type] = [];
            for (let i = start.getDate(); i <= end.getDate(); i++) {
                const dateStr = `${i.toString().padStart(2, '0')}-${startMonth.toString().padStart(2, '0')}-${startYear}`;
                if (i === end.getDate() && startMonth !== endMonth) {
                // Handle end month
                const endMonthDays = new Date(endYear, endMonth, 0).getDate();
                for (let j = 1; j <= end.getDate(); j++) {
                    const dateStr = `${j.toString().padStart(2, '0')}-${endMonth.toString().padStart(2, '0')}-${endYear}`;
                    const rate = ratesByType[type].find(r => r.created_at === dateStr);
                    ratesForRange[type].push(rate ? rate.rate : '');
                }
                } else {
                // Handle start month and other months in range
                const rate = ratesByType[type].find(r => r.created_at === dateStr);
                ratesForRange[type].push(rate ? rate.rate : '');
                }
            }
            });
            // Generate labels for chart
            const labels = [];
            for (let i = start.getDate(); i <= end.getDate(); i++) {
                if (i === end.getDate() && startMonth !== endMonth) {
                    // Handle end month
                    const endMonthDays = new Date(endYear, endMonth, 0).getDate();
                    for (let j = 1; j <= end.getDate(); j++) {
                    labels.push(`${j.toString().padStart(2, '0')}-${endMonth.toString().padStart(2, '0')}-${endYear}`);
                    }
                } else {
                    // Handle start month and other months in range
                    labels.push(`${i.toString().padStart(2, '0')}-${startMonth.toString().padStart(2, '0')}-${startYear}`);
                }
            }

            // Generate datasets for chart
            const datasets = [];
            Object.keys(ratesForRange).forEach(type => {
                datasets.push({
                    label: `${this.paymentMethodsConst[type]}`,
                    data: ratesForRange[type],
                    borderColor: this.colors[type],
                    fill: false
                });
            });

            setTimeout(() => {
                const ctx = document.getElementById("currency-history-chart");
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: datasets
                    },
                });
            }, 300);
        }
    },
    created() {
        this.$store.dispatch('updateListQueue', { 'name': this.section });
    },
    validations: {
        filters: {
            date_from: {},
            date_to: {},
        },
    },
    methods: {
        fetchRateLogs() {
            this.isLoading = true;
            this.submit(route('api.currency.history.list') + '?filters=' + JSON.stringify(this.filters), 'get', this.section, false, false)
        },
        resetSarch() {
            var currentDate = new Date();
            this.filters.date_to =this.formatDate(new Date(currentDate.setDate(currentDate.getDate() + 3)));
            this.filters.date_from =this.formatDate(new Date(currentDate.setDate(currentDate.getDate() - 6)));
        },
        updateCurrencyId(id){
            this.filters.currency_id = id;
        },
        updateServiceId(id){
            this.filters.service_id = id;
        },
        successHandler(response) {
            this.isLoading = false;
            this.rateHistory = response.payload.data;
        },
        formatDate($date) {
            let d = new Date($date);
            let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
            let mo = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(d);
            let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
            return(`${da}-${mo}-${ye}`);
        },
        errorHandler(error){
            this.isLoading = false;
            this.hasError = true;
            // this.error = error.message;
        }
    },
}
</script>
