<template>
    <div class="row p-t-25 text-left">
        <div class="col bg-white padding-40 b-rad-lg">
            <div class="row" v-if="step === 1">
                <div class="col">
                    <div class="row">
                        <div class="col">
                            <div class="row m-b-15">
                                <div class="col text-danger">
                                    Please check carefully, you will not be able to edit this after confirm
                                </div>
                            </div>
                            <div class="row m-b-15">
                                <div class="col-6 p-r-5">
                                    <validation-wrapper-component :validator="v$.parameters.tin">
                                        <label>TIN</label>
                                        <input class="form-control" name="tin" v-model="parameters.tin">
                                    </validation-wrapper-component>
                                </div>
                                <div class="col-6 p-l-5">
                                    <validation-wrapper-component :validator="v$.parameters.msic_code">
                                        <label>
                                            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="parameters.msic_code">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row m-b-15">
                                <div class="col">
                                    <validation-wrapper-component :validator="v$.parameters.street_one">
                                        <label>Billing Address Line 1</label>
                                        <input class="form-control" name="street_one" v-model="parameters.street_one">
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row m-b-15">
                                <div class="col">
                                    <validation-wrapper-component :validator="v$.parameters.street_two">
                                        <label>Billing Address Line 2</label>
                                        <input class="form-control" name="street_two" v-model="parameters.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$.parameters.district_id">
                                        <label>District</label>
                                        <selectable-component
                                            :endpoint="route('api.address.district.list')"
                                            section="districtListSection"
                                            valueColumn="id"
                                            :labelColumn="['city']"
                                            v-model="parameters.district_id"
                                        />
                                    </validation-wrapper-component>
                                </div>
                                <div class="col-5 p-l-5">
                                    <validation-wrapper-component :validator="v$.parameters.post_code">
                                        <label>Post Code</label>
                                        <input class="form-control" name="post_code" v-model="parameters.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$.parameters.state_id">
                                        <label>State</label>
                                        <selectable-component
                                            :endpoint="route('api.address.state.list')"
                                            section="stateListSection"
                                            valueColumn="id"
                                            :labelColumn="['state']"
                                            v-model="parameters.state_id"
                                        />
                                    </validation-wrapper-component>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row m-b-15">
                        <div class="col">
                            <div class="row">
                                <div class="col text-right">
                                    <button
                                        type="button"
                                        class="btn btn-success btn-block b-rad-none"
                                        @click="updateStep(2)"
                                    >
                                        Update E-Invoice Info
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col text-right">
                            <a
                                id="e-invoice-request-link"
                                href="javascript:void(0);"
                                class="fs-12 text-complete text-underline pointer"
                                @click="updateChangeOfMind"
                            >
                                I don't need now
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row" v-if="step === 2">
                <div class="col">
                    <div class="row m-b-15">
                        <div class="col">
                            <div class="row m-b-15">
                                <div class="col text-danger">
                                    Please check carefully, you will not be able to edit this after confirm
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <div class="padding-15 bg-master-lightest">
                                        <p class="muted">TIN</p>
                                        <p class="m-b-0">{{ parameters.tin }}</p>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <div class="padding-15 bg-master-lightest" v-if="parameters.msic_code !== 0 && parameters.msic_code !== '0'">
                                        <p class="muted">MSIC Code</p>
                                        <p class="m-b-0">{{ parameters.msic_code }}</p>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <div class="padding-15 bg-master-lightest">
                                        <p class="muted">Billing Address</p>
                                        <p class="m-b-0">
                                            {{ parameters.street_one }} {{ parameters.street_two }},
                                            {{ selectedDistrict?.city }} {{ parameters.post_code }}
                                            {{ selectedState?.state }}, {{ selectedDistrict?.country.name }}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row m-b-15">
                        <div class="col">
                            <div class="row">
                                <div class="col-auto p-r-5">
                                    <button type="button" class="btn bg-master-lighter b-rad-none" @click="updateStep(1)">Edit E-Invoice Info</button>
                                </div>
                                <div class="col p-l-0">
                                    <button type="button" class="btn btn-success btn-block b-rad-none" @click="submitForm">Confirm E-Invoice Info</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

interface District {
    id: number;
    city: string;
    country: { name: string };
}

interface State {
    id: number;
    state: string;
}

interface Props {
    companyId: number;
    companyType: number;
}

const props = defineProps<Props>();
const emit = defineEmits(['eInvoiceInfoUpdated', 'eInvoiceChangeOfMindRequest']);

const step = ref(1);
const section = ref('einvoiceInfoSection');
const queueStore = useQueueStore();

const mustContainLetterAndNumber = (value: string) => {
    if (!value) return true;
    const hasLetter = /[a-zA-Z]/.test(value);
    const hasNumber = /\d/.test(value);
    return hasLetter && hasNumber;
};

const notZero = (value: any) => {
    return value !== 0 && value !== '0' && value !== null && value !== undefined;
};

const fiveDigits = (value: any) => {
    return /^\d{5}$/.test(value);
};

const allowZeroOrFiveDigits = (value: any) => {
    return Number(value) === 0 || /^\d{5}$/.test(value);
};

const rules = computed(() => {
    return {
        parameters: {
            street_one: { required },
            street_two: {},
            district_id: { required },
            state_id: { required },
            post_code: {
                notZero: helpers.withMessage('Postcode cannot be empty', notZero),
                fiveDigits: helpers.withMessage('Postcode must be 5 digits', fiveDigits)
            },
            tin: {
                ...(props.companyType === 0
                    ? {
                        required,
                        alphaNum,
                        minLength: minLength(10),
                        maxLength: maxLength(13)
                    }
                    : {}),
                ...(props.companyType === 1
                    ? {
                        required,
                        alphaNum,
                        minLength: minLength(10),
                        maxLength: maxLength(13)
                    }
                    : {})
            },
            msic_code: props.companyType === 1
                ? {
                    notZero: helpers.withMessage('MSIC Code cannot be empty', notZero),
                    fiveDigits: helpers.withMessage('MSIC Code must be 5 digits', fiveDigits)
                }
                : {
                    allowZeroOrFiveDigits: helpers.withMessage('MSIC Code must be 5 digits or 0', allowZeroOrFiveDigits)
                },
        }
    };
});

const { parameters, submit, closeModal } = useFormHandler({
    section: section.value,
    data: {
        company_id: props.companyId,
        street_one: '',
        street_two: '',
        district_id: '',
        state_id: '',
        post_code: '',
        tin: '',
        msic_code: '',
    }
});

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

const districts = computed<District[]>(() => queueStore.getSelectableList('original_districtListSection'));
const states = computed<State[]>(() => queueStore.getSelectableList('original_stateListSection'));

const selectedDistrict = computed(() => {
    if (!parameters.value.district_id) return null;
    return districts.value.find(d => d.id === parseInt(parameters.value.district_id));
});

const selectedState = computed(() => {
    if (!parameters.value.state_id) return null;
    return states.value.find(s => s.id === parseInt(parameters.value.state_id));
});

const updateStep = async (newStep: number) => {
    if (newStep === 2) {
        const isValid = await v$.value.$validate();
        if (!isValid) return;
    }
    step.value = newStep;
};

const submitForm = () => {
    submit(route('api.company.einvoice.info.update'), 'post', section.value, true, true, parameters.value, {
        successHandler: (result: any) => {
            emit('eInvoiceInfoUpdated', result.payload.data);
            if (closeModal) closeModal();
        }
    });
};

const updateChangeOfMind = () => {
    emit('eInvoiceChangeOfMindRequest');
    if (closeModal) closeModal();
};
</script>

