<template>
    <div class="row" style="width: 450px; margin: auto;" @keyup.enter="submitForm">
        <div class="col bg-white padding-40 b-rad-lg">
            <div class="row m-b-10">
                <div class="col text-center">
                    <h3>Edit Company Details</h3>
                </div>
            </div>
            <div class="row m-b-15">
                <div class="col">
                    <validation-wrapper-component :validator="v$.params.name">
                        <label class="text-primary">Name</label>
                        <input class="form-control" v-model="params.name">
                    </validation-wrapper-component>
                </div>
            </div>
            <div class="row m-b-15">
                <div class="col">
                    <validation-wrapper-component :validator="v$.params.debtor">
                        <label class="text-primary">Debtor Code</label>
                        <input class="form-control" v-model="params.debtor">
                    </validation-wrapper-component>
                </div>
            </div>

            <div class="row m-b-15">
                <div class="col">
                    <validation-wrapper-component :validator="v$.params.identification_reference">
                        <label class="text-primary">{{ data.type === 0 ? 'Identification Card' : 'SSM Registration' }}</label>
                        <input class="form-control" v-model="params.identification_reference">
                    </validation-wrapper-component>
                </div>
            </div>

            <div class="row m-b-5" v-if="data.e_invoice !== 0 && data.e_invoice !== null">
                <div class="col">
                    E-Invoice Info
                    <div class="row m-b-15">
                        <div class="col-6 p-r-5">
                            <validation-wrapper-component :validator="v$.params.tin">
                                <label class="text-primary">TIN</label>
                                <input class="form-control" v-model="params.tin">
                            </validation-wrapper-component>
                        </div>
                        <div class="col-6 p-l-5">
                            <validation-wrapper-component :validator="v$.params.msic_code">
                                <label class="text-primary">
                                    MSIC Code
                                    <a href="https://sdk.myinvois.hasil.gov.my/codes/msic-codes/" target="_blank" rel="noopener noreferrer">
                                        (View List)
                                    </a>
                                </label>
                                <input class="form-control" name="msic_code" v-model="params.msic_code">
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row m-b-15">
                        <div class="col">
                            <validation-wrapper-component :validator="v$.params.street_one">
                                <label class="text-primary">Billing Address Line 1</label>
                                <input class="form-control" name="street_one" v-model="params.street_one">
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row m-b-15">
                        <div class="col">
                            <validation-wrapper-component :validator="v$.params.street_two">
                                <label class="text-primary">Billing Address Line 2</label>
                                <input class="form-control" name="street_two" v-model="params.street_two">
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row m-b-15">
                        <div class="col-7 p-r-5">
                            <validation-wrapper-component selectable :validator="v$.params.district_id">
                                <label class="text-primary">District</label>
                                <selectable-component :endpoint="route('api.address.district.list')" section="districtListSection" valueColumn="id" :labelColumn="['city']" v-model="params.district_id"></selectable-component>
                            </validation-wrapper-component>
                        </div>
                        <div class="col-5 p-l-5">
                            <validation-wrapper-component :validator="v$.params.post_code">
                                <label class="text-primary">Post Code</label>
                                <input class="form-control" v-model="params.post_code">
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row m-b-15">
                        <div class="col-6 p-r-5">
                            <validation-wrapper-component selectable :validator="v$.params.state_id">
                                <label class="text-primary">State</label>
                                <selectable-component :endpoint="route('api.address.state.list')" section="stateListSection" valueColumn="id" :labelColumn="['state']" v-model="params.state_id"></selectable-component>
                            </validation-wrapper-component>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row m-t-15">
                <div class="col-auto p-r-5">
                    <div class="btn btn-lg btn-default b-rad-none" data-dismiss="modal">Cancel</div>
                </div>
                <div class="col p-l-5">
                    <div class="btn btn-primary w-100 btn-lg" @click="submitForm">Confirm</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, reactive } from 'vue';
import { useQueueStore } from '@/stores/queue';
import { useFormHandler } from '@/composables/useFormHandler';
import { useVuelidate } from '@vuelidate/core';
import { alphaNum, maxLength, minLength, required } from '@vuelidate/validators';
import route from '@/general/functions/router';

interface Props {
    section: string;
    data: Record<string, any>;
}

const props = defineProps<Props>();
const data = props.data;
const queueStore = useQueueStore();
const { submit, closeModal } = useFormHandler(props);

const params = reactive({
    id: data.id,
    reference: data.reference,
    type: data.type,
    name: data.name,
    debtor: data.debtor,
    tin: data.tin,
    msic_code: data.msic_code,
    address_id: data.address_einvoice ? data.address_einvoice.id : null,
    street_one: data.address_einvoice ? data.address_einvoice.street_one : null,
    street_two: data.address_einvoice ? data.address_einvoice.street_two : null,
    district_id: data.address_einvoice ? data.address_einvoice.district.id : null,
    state_id: data.address_einvoice ? data.address_einvoice.state.id : null,
    post_code: data.address_einvoice ? data.address_einvoice.post_code : null,
    identification_id: data.identification ? data.identification.id : null,
    identification_reference: data.identification ? data.identification.reference : null
});

const notZero = (value: any) => value !== 0 && value !== '0' && value !== null && value !== undefined;
const fiveDigits = (value: any) => /^\d{5}$/.test(value);
const allowZeroOrFiveDigits = (value: any) => Number(value) === 0 || /^\d{5}$/.test(value);

const rules = computed(() => {
    const companyType = data.type;
    const isEInvoiceEnabled = data.e_invoice !== 0 && data.e_invoice !== null;

    return {
        params: {
            name: { required },
            debtor: {},
            tin: isEInvoiceEnabled
                ? {
                    ...(companyType === 0 ? { required, alphaNum, minLength: minLength(10), maxLength: maxLength(13) } : {}),
                    ...(companyType === 1 ? { required, alphaNum, minLength: minLength(10), maxLength: maxLength(13) } : {})
                }
                : {},
            msic_code: isEInvoiceEnabled && companyType === 1 ? { notZero, fiveDigits } : { allowZeroOrFiveDigits },
            address_id: {},
            street_one: isEInvoiceEnabled ? { required } : {},
            street_two: {},
            district_id: isEInvoiceEnabled ? { required } : {},
            state_id: isEInvoiceEnabled ? { required } : {},
            post_code: isEInvoiceEnabled ? { notZero, fiveDigits } : {},
            identification_reference: {}
        }
    };
});

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

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

    submit(route('api.company.update.details', data.id), 'put', props.section, true, true, params, {
        successHandler: () => {
            queueStore.reloadList({ name: 'customerProfileSection' });
            closeModal();
        }
    });
};
</script>
