<template>
    <div class="row">
        <div class="col">
            <div class="row m-b-15" v-for="(item, index) in serviceCurrencies" :key="item.id">
                <div class="col">
                    <div class="row">
                        <div class="col-3 b-a pointer p-t-20 p-b-20" :class="[{ 'b-success': item.active }, { 'b-grey': !item.active }]" @click="item.active = !item.active">
                            <div class="absolute" style="top: -10px; right: -27px;" v-if="item.active">
                                <div class="icon-thumbnail icon-25 bg-success text-white btn-rounded fs-10">
                                    <i class="fa fs-10 fa-check"></i>
                                </div>
                            </div>
                            <currency-component :deleteable="false" :section="section" :data="item.currency_object"></currency-component>
                        </div>
                        <div class="col">
                            <div class="row h-100 m-r-0 align-items-end" v-if="v$?.parameters?.currencies?.[index]" v-show="item.active">
                                <div class="col p-t-15 b-t b-r b-success bg-master-lightest">
                                    <div class="row m-b-10">
                                        <div class="col">
                                            <div class="font-heading all-caps fs-10 hint-text muted">
                                                Purchase Limits
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row m-r-0">
                                        <div class="col m-r-10 p-r-5">
                                            <div class="row">
                                                <div class="col p-r-0">
                                                    <validation-wrapper-component class="no-border" :validator="v$?.parameters?.currencies?.[index]?.minimum_limit?.value">
                                                        <label>Minimum Limit</label>
                                                        <input type="text" class="form-control" v-model.lazy="item.minimum_limit.value" v-money3="money" :disabled="!item.active">
                                                    </validation-wrapper-component>
                                                </div>
                                                <div class="col-auto bg-white b-t b-r b-b b-grey">
                                                    <div class="row h-100 align-items-center">
                                                        <div class="col">
                                                            <div class="font-heading fs-10 muted">{{ item.currency_object.short_code }}</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col p-l-5">
                                            <div class="row">
                                                <div class="col p-r-0">
                                                    <validation-wrapper-component :validator="v$?.parameters?.currencies?.[index]?.maximum_limit?.value">
                                                        <label>Maximum Limit</label>
                                                        <input type="text" class="form-control" v-model.lazy="item.maximum_limit.value" v-money3="money" :disabled="!item.active">
                                                    </validation-wrapper-component>
                                                </div>
                                                <div class="col-auto bg-white b-t b-r b-b b-grey">
                                                    <div class="row h-100 align-items-center">
                                                        <div class="col">
                                                            <div class="font-heading fs-10 muted">{{ item.currency_object.short_code }}</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row m-r-0" v-if="v$?.parameters?.currencies?.[index]" v-show="item.active">
                        <div class="col p-b-15 bg-master-lightest b-r b-b b-l b-success">
                            <div class="row">
                                <div class="col p-r-25 p-l-25">
                                    <div class="row m-b-10 m-t-10">
                                        <div class="col p-l-5">
                                            <div class="font-heading all-caps fs-10 hint-text muted">
                                                Exchange Rates
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-4 p-l-5 p-r-5 m-b-10" v-for="(rate, method) in item.rates" :key="method">
                                            <validation-wrapper-component :validator="v$?.parameters?.currencies?.[index]?.rates?.[method]?.selling?.value">
                                                <label class="all-caps">{{ rate.payment_method }}</label>
                                                <input type="text" class="form-control" v-model.lazy="rate.selling.value" v-money3="exchangeRate" :disabled="!item.active">
                                            </validation-wrapper-component>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useQueueStore } from '@/stores/queue';
import useVuelidate from '@vuelidate/core';
import { requiredIf, minValue } from '@vuelidate/validators';

interface CurrencyLike {
    id: number;
    short_code?: string;
}

interface Rate {
    payment_method: string;
    selling: {
        type: string;
        value: string;
    };
}

interface ServiceCurrency {
    id: number;
    currency_object: CurrencyLike;
    active: boolean;
    maximum_limit: { type: string; value: number };
    minimum_limit: { type: string; value: number };
    rates: Record<number, Rate>;
}

interface Props {
    section: string;
    data: {
        currencies: ServiceCurrency[];
    };
    modelValue?: ServiceCurrency[];
}

const props = defineProps<Props>();
const emit = defineEmits<{
    (e: 'update:modelValue', value: ServiceCurrency[]): void;
}>();

const queueStore = useQueueStore();

const money = { decimal: '.', thousands: ',', precision: 2 };
const exchangeRate = { decimal: '.', thousands: '', precision: 5 };

const parameters = ref({
    currencies: props.data?.currencies || []
});

const rules = computed(() => {
    const curRules: any = {};
    parameters.value.currencies.forEach((currency: any, index: number) => {
        curRules[index] = {
            maximum_limit: {
                value: { required: requiredIf(() => currency.active) }
            },
            minimum_limit: {
                value: { required: requiredIf(() => currency.active) }
            },
            rates: (() => {
                const rateRules: any = {};
                //console.log(currency.rates) //mixture of arrays and objects
                // currency.rates.forEach((rate: any, rIndex: number) => {
                //     rateRules[rIndex] = {
                //         selling: {
                //             value: { required: requiredIf(() => currency.active), minValue: minValue(0) }
                //         }
                //     };
                // });

                Object.entries(currency.rates || {}).forEach(([key, rate]: [string, any]) => {
                    rateRules[key] = {
                        selling: {
                            value: {
                                required: requiredIf(() => currency.active),
                                minValue: minValue(0)
                            }
                        }
                    };
                });
                //    console.log('FIX: ' , rateRules)
                return rateRules;
            })()
        };
    });
    return {
        parameters: {
            currencies: curRules
        }
    };
});

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

const availableCurrencies = computed(() => queueStore.getListData('convertibleCurrenciesSection'));
const serviceCurrencies = computed(() => parameters.value.currencies);

const inArray = (element: CurrencyLike): boolean => {
    return parameters.value.currencies.some((currency) => currency.id === element.id);
};

const pushIfNotExist = (element: ServiceCurrency) => {
    if (!inArray(element)) {
        parameters.value.currencies.push(element);
    }
};

const addInactiveCurrency = (element: CurrencyLike) => {
    pushIfNotExist({
        currency_object: element,
        active: false,
        id: element.id,
        maximum_limit: {
            type: 'fixed_amount',
            value: 0
        },
        minimum_limit: {
            type: 'fixed_amount',
            value: 0
        },
        rates: {
            0: { payment_method: 'cash', selling: { type: 'rate', value: "0" } },
            1: { payment_method: 'cheque', selling: { type: 'rate', value: "0" } },
            2: { payment_method: 'ba', selling: { type: 'rate', value: "0" } },
            3: { payment_method: 'wallet', selling: { type: 'rate', value: "0" } },
            4: { payment_method: 'payment_gateway', selling: { type: 'rate', value: "0" } }
        }
    });
};
// const syncCurrencies = (available: CurrencyLike[] = []) => {
//     parameters.value.currencies = available.map((currency) => ({
//         currency_object: currency,
//         active: false,
//         id: currency.id,
//         maximum_limit: { type: 'fixed_amount', value: 0 },
//         minimum_limit: { type: 'fixed_amount', value: 0 },
//         rates: [
//             { payment_method: 'cash', selling: { type: 'rate', value: 0 } },
//             { payment_method: 'cheque', selling: { type: 'rate', value: 0 } },
//             { payment_method: 'ba', selling: { type: 'rate', value: 0 } },
//             { payment_method: 'wallet', selling: { type: 'rate', value: 0 } },
//             { payment_method: 'payment_gateway', selling: { type: 'rate', value: 0 } }
//         ]
//     }));
// };
// watch(
//     () => props.data,
//     (value) => {
//         parameters.value = {
//             currencies: value?.currencies || []
//         };
//         // if(parameters.value && parameters.value.currencies && parameters.value.currencies.length === 0) {
//         //     syncCurrencies(queueStore.getListData('convertibleCurrenciesSection'));
//         // }
//     },
//     { deep: true, immediate: true }
// );
watch(
    () => props.data?.currencies,
    (currencies) => {
        if (!currencies) return;

        // parameters.value.currencies = currencies;
        // if (currencies.length === 0) {
        //     syncCurrencies(queueStore.getListData('convertibleCurrenciesSection'));
        // }

        queueStore.getListData('convertibleCurrenciesSection').forEach((currency: CurrencyLike) => addInactiveCurrency(currency));
    },
    // { deep: true }
);

watch(
    availableCurrencies,
    (currencies) => {
        currencies.forEach((currency: CurrencyLike) => addInactiveCurrency(currency));
    },
    { deep: true, immediate: true }
);

watch(
    serviceCurrencies,
    (currencies) => {
        emit('update:modelValue', currencies);
    },
    { deep: true }
);
</script>
