<template>
    <div class="row p-t-25 text-left">
        <div class="col">
            <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">
                                    <validation-wrapper-component :validator="v$.parameters.street_one">
                                        <label>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>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>
                    </div>
                    <div class="row m-b-15">
                        <div class="col">
                            <div class="row">
                                <div class="col text-right">
                                    <button
                                        type="button"
                                        class="btn btn-sm btn-success btn-block b-rad-none"
                                        @click="updateStep(2)"
                                    >
                                        {{ (props.type === 3) ? "Update" : "Save" }} Billing Address
                                    </button>
                                    <button
                                        v-show="props.type === 3"
                                        type="button"
                                        class="btn btn-sm bg-master-lighter b-rad-none m-l-5"
                                        @click="closeForm"
                                    >
                                        Cancel
                                    </button>
                                </div>
                            </div>
                        </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">
                                <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 }}
                                            {{ selectedDistrict?.state.name }}, {{ 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 btn-sm bg-master-lighter b-rad-none" @click="updateStep(1)">Edit Billing Address</button>
                                </div>
                                <div class="col p-l-0">
                                    <button type="button" class="btn btn-sm btn-success btn-block b-rad-none" @click="submitForm">Confirm Billing Address</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useRequest } from '@/composables/useRequest';
import { required } from '@vuelidate/validators';
import { useQueueStore } from '@/stores/queue';
import { useVuelidate } from '@vuelidate/core';
import route from '@/general/functions/router';
import emitter from '@/utils/emitter';

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

interface Props {
    id: number;
    type?: number; // 1 = create, 2 = update set default, 3 = update address
    addressData?: any;
}

const props = withDefaults(defineProps<Props>(), {
    type: 1,
    addressData: () => ({})
});

const emit = defineEmits(['addressFormUpdated', 'createdAddress', 'updateDefaultAddress', 'close']);

const step = ref(1);
const queueStore = useQueueStore();
const rules = {
    parameters: {
        street_one: { required },
        street_two: {},
        district_id: { required },
        post_code: { required },
    }
};

const { submit } = useRequest();

const parameters = ref({
    company_id: props.id,
    street_one: props.addressData?.street_one || '',
    street_two: props.addressData?.street_two || '',
    district_id: props.addressData?.district?.id || '',
    post_code: props.addressData?.post_code || '',
});

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

const districts = computed<District[]>(() => {
    return queueStore.getSelectableList('original_districtListSection');
});

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

watch(() => props.id, (newId) => {
    parameters.value.company_id = newId;
});

watch(() => props.addressData, (newData) => {
    if (newData) {
        parameters.value = {
            company_id: props.id,
            street_one: newData.street_one,
            street_two: newData.street_two,
            district_id: newData.district?.id || '',
            post_code: newData.post_code,
        };
    }
}, { deep: true });

const resetForm = () => {
    parameters.value = {
        company_id: props.id,
        street_one: '',
        street_two: '',
        district_id: '',
        post_code: '',
    };
    step.value = 1;
    v$.value.$reset();
};

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

const submitForm = () => {
    let url = '';
    let method = '';

    if (props.type === 3) {
        url = route('api.address.update', props.addressData.id);
        method = 'put';
    } else {
        url = route('api.address.create');
        method = 'post';
    }

    submit(url, method, 'bookingDetailSection', true, true, parameters.value, {
        successHandler: (result: any) => {
            if (props.type === 3) {
                closeForm();
                queueStore.reloadList({ name: "addresslist" });
                emit('addressFormUpdated');
            } else {
                if (props.type !== 2) {
                    emit('updateDefaultAddress', result.payload.data);
                } else {
                    emit('createdAddress', result.payload.data);
                }
                resetForm();
            }
        }
    });
};

const closeForm = () => {
    emitter.emit('updateAddressForm', { address: {}, status: false });
};
</script>

