<template>
    <div class="row">
        <div class="col">
            <loading-component style="height: 50px; top: 0;" key="1" color="success" v-show="isLoading" />
            <div class="row" v-show="!isLoading">
                <div class="col">
                    <div class="row m-b-20" v-if="type !== 2">
                        <div class="col">
                            <h6 class="all-caps m-b-5 bold no-margin">Add Bank Account</h6>
                        </div>
                    </div>
                    <div class="row m-b-5 animate__animated animate__fadeInUpBig animate__fast" v-if="error">
                        <div class="col">
                            <small class="bold fs-10 text-danger">{{ error }}</small>
                        </div>
                    </div>
                    <div class="row" v-if="currency !== 'USD'">
                        <div class="col">
                            <div class="row m-b-10" v-if="type === 2">
                                <div class="col">
                                    <validation-wrapper-component :validator="v$.parameters.reference">
                                        <label>Reference</label>
                                        <input type="text" class="form-control" v-model="parameters.reference" :disabled="disabled">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row m-b-10">
                                <div class="col">
                                    <validation-wrapper-component :validator="v$.parameters.holder_name">
                                        <label>Account Holder Name / Company Name</label>
                                        <input type="text" class="form-control" v-model="parameters.holder_name" :disabled="disabled">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row m-b-10">
                                <div class="col">
                                    <validation-wrapper-component :validator="v$.parameters.account_no">
                                        <label>{{ serviceType ? serviceType.id === 4 ? 'Alipay recipient Email / Phone' : 'Account No.' : 'Account No.'}}</label>
                                        <input type="text" class="form-control" v-model="parameters.account_no" :disabled="disabled">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row" v-if="type === 2">
                                <div class="col">
                                    <div class="row m-b-10">
                                        <div class="col">
                                            <validation-wrapper-component :validator="v$.parameters.bank_name">
                                                <label>Bank Name</label>
                                                <input type="text" class="form-control" v-model="parameters.bank_name" :disabled="disabled">
                                            </validation-wrapper-component>
                                        </div>
                                    </div>
                                    <div class="row m-b-10">
                                        <div class="col">
                                            <validation-wrapper-component :validator="v$.parameters.bank_branch">
                                                <label>Bank Branch / 所在地</label>
                                                <input type="text" class="form-control" v-model="parameters.bank_branch" :disabled="disabled">
                                            </validation-wrapper-component>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row" v-if="currency === 'USD'">
                        <div class="col">
                            <div class="row m-b-10">
                                <div class="col">
                                    <validation-wrapper-component :validator="v$.parameters.holder_name">
                                        <label>Account Holder Name</label>
                                        <input type="text" class="form-control" v-model="parameters.holder_name" :disabled="disabled">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row m-b-10">
                                <div class="col">
                                    <validation-wrapper-component :validator="v$.parameters.reference">
                                        <label>Account Holder Address</label>
                                        <input type="text" class="form-control" v-model="parameters.reference" :disabled="disabled">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row m-b-10">
                                <div class="col">
                                    <validation-wrapper-component :validator="v$.parameters.account_no">
                                        <label>Account No</label>
                                        <input type="text" class="form-control" v-model="parameters.account_no" :disabled="disabled">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row" v-if="type === 2">
                                <div class="col">
                                    <div class="row m-b-10">
                                        <div class="col">
                                            <validation-wrapper-component :validator="v$.parameters.bank_name">
                                                <label>Bank Name</label>
                                                <input type="text" class="form-control" v-model="parameters.bank_name" :disabled="disabled">
                                            </validation-wrapper-component>
                                        </div>
                                    </div>
                                    <div class="row m-b-10">
                                        <div class="col">
                                            <validation-wrapper-component :validator="v$.parameters.bank_branch">
                                                <label>Bank Address</label>
                                                <input type="text" class="form-control" v-model="parameters.bank_branch" :disabled="disabled">
                                            </validation-wrapper-component>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row m-b-10" >
                                <div class="col p-r-5">
                                    <validation-wrapper-component :validator="v$.parameters.swift">
                                        <label>Swift</label>
                                        <input type="text" class="form-control" v-model="parameters.swift" :disabled="disabled">
                                    </validation-wrapper-component>
                                </div>
                                <div class="col p-l-5 hide">
                                    <validation-wrapper-component :validator="v$.parameters.snap">
                                        <label>Snap</label>
                                        <input type="text" class="form-control" v-model="parameters.snap" :disabled="disabled">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row m-b-20" v-if="type !== 2">
                        <div class="col">
                            <validation-wrapper-component selectable :validator="v$.parameters.bank_name">
                                <label>Bank Name</label>
                                <selectable-component :endpoint="asset('malaysian_banks.json')" section="banksListSection" valueColumn="name" :labelColumn="['name']" v-model="parameters.bank_name" />
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col" :class="[{'p-r-15': disabled}, {'p-r-5': !disabled}]" v-if="!isCancelButtonHidden">
                            <div class="btn btn-sm btn-default bg-master-lightest btn-block b-rad-none" @click="handleCancel">{{ disabled ? 'Change Recipient Account' : 'Cancel' }}</div>
                        </div>
                        <div class="col p-l-5" v-if="!disabled && !isEditing">
                            <div class="btn btn-sm btn-success btn-block b-rad-none" @click="submitForm">Add Account</div>
                        </div>
                        <div class="col p-l-5" v-if="isEditing">
                            <div class="btn btn-sm btn-success btn-block b-rad-none" @click="submitForm">Update Details</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { watch } from 'vue';
import { useFormHandler } from '@/composables/useFormHandler';
import { required, requiredIf } from '@vuelidate/validators';
import { useVuelidate } from '@vuelidate/core';
import route from '@/general/functions/router';

interface Props {
    id?: number;
    company_id?: number;
    type?: number;
    closable?: boolean;
    disabled?: boolean;
    country_id?: number;
    serviceType?: any;
    currency?: string;
    isEditing?: boolean;
    isCancelButtonHidden?: boolean;
    billNo?: string;
    transactionId?: number;
    section: string;
    data?: any;
}

const props = withDefaults(defineProps<Props>(), {
    company_id: 1,
    type: 1,
    closable: true,
    disabled: false,
    country_id: 1,
    serviceType: null,
    currency: 'RMB',
    isEditing: false,
    isCancelButtonHidden: false,
    billNo: '',
    transactionId: 0
});

const emit = defineEmits(['close', 'updatedBankDetails', 'createdBank']);

const requiredIfAccountTypeTwo = (requiredIf as any)((_value: any, sibling: any) => {
    return sibling.account_type === 2;
});

const rules = {
    parameters: {
        holder_name: {
            required
        },
        account_no: {
            required
        },
        bank_name: {
            required
        },
        reference: {
            required: requiredIfAccountTypeTwo
        }
    }
};

const { submit, error, isLoading, closeModal, parameters, formHandler } = useFormHandler(props);

const defaults = {
    id: props.data?.id,
    company_id: props.company_id,
    account_type: props.type,
    reference: props.data?.reference || '',
    bank_name: props.data?.bank_name || '',
    holder_name: props.data?.holder_name || '',
    account_no: props.data?.account_no || '',
    bank_branch: props.data?.bank_branch || '',
    swift: props.data?.swift || '',
    snap: props.data?.snap || '',
    country_id: props.country_id,
    bill_no: props.billNo,
    transaction_id: props.transactionId,
};

const syncFromProps = () => {
    if (!props.isEditing && (!props.data || props.data === undefined)) {
        Object.assign(parameters.value, defaults);
    }
};

const resetForm = () => {
    Object.assign(parameters.value, defaults);
    v$.value.$reset();
};

watch(() => props.data, syncFromProps, { immediate: true });

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

const handleCancel = () => {
    if (!props.isEditing && (!props.data || props.data === undefined)) {
        closeModal();
    }
    else{
        emit('close')
    }
};

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

const submitForm = async () => {
    const isValid = await v$.value.$validate();
    if (!isValid) return;

    if (props.isEditing) {
        parameters.value.company_id = props.company_id;
        parameters.value.account_type = props.type;
        parameters.value.bill_no = props.billNo;
        parameters.value.transaction_id = props.transactionId;

        submit(route('api.bank.update', parameters.value.id), 'put', props.section, true, false, parameters.value, {
            successHandler: (response: any) => {
                if (props.type !== 2) {
                    closeModal();
                } else {
                    // closeModal();
                    emit('updatedBankDetails', response.payload.data, props.transactionId);
                }
                formHandler();
                resetForm();
            }
        });
    } else {
        submit(route('api.bank.create'), 'post', props.section, true, false, parameters.value, {
            successHandler: (response: any) => {
                if (props.type !== 2) {
                    closeModal();
                } else {
                    // closeModal();
                    emit('createdBank', response.payload.data);
                }
                formHandler();
                resetForm();
            }
        });
    }
};
</script>
