<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 m-b-10">
                        <div class="col">
                            <validation-wrapper-component :validator="v$.parameters.account_no">
                                <label>{{ serviceType?.id === 4 ? '1688 Login Id/Email/Phone' : 'Account No.' }}</label>
                                <input type="text" class="form-control" v-model="parameters.account_no" :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>1688 Login Password</label>
                                <input type="text" class="form-control" v-model="parameters.holder_name" @keyup="onlyChinese" :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>AliPay 6-digit Payment Pin</label>
                                <input type="text" class="form-control" v-model="parameters.bank_branch" :disabled="disabled">
                            </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="$emit('close')">{{ disabled ? 'Change Recipient Account' : 'Cancel' }}</div>
                        </div>
                        <div class="col p-l-5" v-if="!disabled && !isEditing">
                            <button class="btn btn-sm btn-success btn-block b-rad-none" @click="submitForm">Add Account</button>
                        </div>
                        <div class="col p-l-5" v-if="isEditing">
                            <button class="btn btn-sm btn-success btn-block b-rad-none" @click="submitForm">Update Details</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

interface Props {
    company_id?: number;
    type?: number;
    closable?: boolean;
    disabled?: boolean;
    country_id?: number;
    serviceType?: any;
    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,
    isEditing: false,
    isCancelButtonHidden: false,
    billNo: '',
    transactionId: 0
});

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

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

const rules = {
    parameters: {
        holder_name: { required },
        account_no: { required },
        bank_branch: { required }
    }
};

const defaults = {
    id: props.data?.id,
    company_id: props.company_id,
    account_type: 3,
    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 || '',
    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);
    }
};
// syncFromProps();

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

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

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

const englishTextWarning = ref(false);

const onlyChinese = (event: Event) => {
    const target = event.target as HTMLInputElement;
    const value = target.value;
    const regex = /^[^~`!@#$%^&*()_+=[\]\{}|;':",.\/<>?a-zA-Z0-9-]+$/;

    englishTextWarning.value = !regex.test(value);
};

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

    parameters.value.account_type = 3;
    parameters.value.bank_name = '-';

    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>
