<template>
    <div class="row" @keyup.enter="submitForm">
        <div class="col">
            <div class="row">
                <div class="col">
                    <div class="row m-b-10">
                        <div class="col">
                            <h3 class="all-caps m-b-5 no-margin text-center">Edit Company Type</h3>
                            <div class="fs-11 text-center">Please double confirm before ediiting the Company Type</div>
                        </div>
                    </div>
                    <div class="row m-b-10">
                        <div class="col">
                            <validation-wrapper-component selectable :validator="v$.parameters.type">
                                <label>Company Type</label>
                                <selectable-component :endpoint="route('api.company.company_type.list')" section="listCompanyTypeSection" valueColumn="id" :labelColumn="['type']" v-model="parameters.type"></selectable-component>
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col p-r-5">
                            <div class="btn btn-sm btn-default bg-master-lightest btn-block b-rad-none" data-dismiss="modal">Cancel</div>
                        </div>
                        <div class="col p-l-5">
                            <div class="btn btn-sm btn-success btn-block b-rad-none" @click="submitForm">Update</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { watch } 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 {
    section: string;
    data: Record<string, any> | null;
}

const props = defineProps<Props>();

const { parameters, submit } = useFormHandler({ section: props.section });

const initParameters = () => {
    if (!props.data) return;
    parameters.value = {
        type: [0, 1].includes(props.data.type) ? props.data.type : 0,
        email: props.data.contact ? props.data.contact.email : '',
        phone: props.data.contact ? props.data.contact.phone : ''
    };
};

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

const rules = {
    parameters: {
        type: { required }
    }
};

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

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

    submit(route('api.company.profile.update', props.data.id), 'put', `${props.section}EditCompanyType`, true, true, parameters.value, {
        successHandler: () => {
            window.location.reload();
        }
    });
};
</script>
