<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">
                <div class="col">
                    <validation-wrapper-component class="m-b-15" :validator="v$.parameters.name">
                        <label class="text-primary">Name</label>
                        <input class="form-control" v-model="parameters.name">
                    </validation-wrapper-component>
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <validation-wrapper-component class="m-b-15" :validator="v$.parameters.debtor">
                        <label class="text-primary">Debtor Code</label>
                        <input class="form-control" v-model="parameters.debtor">
                    </validation-wrapper-component>
                </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 { 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: any;
}

const props = defineProps<Props>();

const { parameters, submit } = useFormHandler({
    section: props.section,
    data: {
        id: props.data?.id,
        name: props.data?.name || '',
        debtor: props.data?.debtor || '',
        reference: props.data?.reference || '',
        type: props.data?.type
    }
});

const rules = {
    parameters: {
        name: { required },
        debtor: {}
    }
};

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

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

    submit(route('api.company.update.nameAndDebtor', props.data.id), 'put', props.section, true, true, parameters.value, {
        successHandler: (response: any) => {
            window.location.replace(route('customers', response.payload.data.reference));
        }
    });
};
</script>
