<template>
    <div>
        <Form @submit="onSubmit" :validation-schema="schema" v-slot="{ errors, isSubmitting }">
            <div class="alert alert-info">
                <i class="fe fe-info me-2"></i>
                Vui lòng xác nhận thông tin duyệt hóa đơn.
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Ghi chú duyệt</label>
                        <Field name="approvalNote" as="textarea" rows="3" v-model="form.approvalNote"
                            class="form-control" :class="{ 'is-invalid': errors.approvalNote }"
                            placeholder="Nhập ghi chú duyệt (tùy chọn)..." @keydown.enter.prevent />
                        <div class="invalid-feedback">{{ errors.approvalNote }}</div>
                    </div>
                </div>


            </div>

            <div class="d-flex justify-content-end gap-2">
                <button type="button" class="btn btn-secondary" @click="$emit('cancel')">Hủy</button>
                <button type="submit" class="btn btn-success" :disabled="isSubmitting">
                    <span v-show="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
                    <i v-show="!isSubmitting" class="fe fe-check me-2"></i>
                    {{ isSubmitting ? 'Đang xử lý...' : 'Xác nhận duyệt' }}
                </button>
            </div>
        </Form>
    </div>
</template>

<script setup>
import { reactive } from 'vue';
import { Form, Field } from 'vee-validate';
import * as Yup from 'yup';

const emit = defineEmits(['confirmed', 'cancel']);

const form = reactive({
    approvalNote: ''
});

const schema = Yup.object().shape({

    approvalNote: Yup.string()
        .nullable()
        .transform(v => (v === undefined || v === null ? '' : v))
        .test('min-if-provided', 'Ghi chú duyệt phải có ít nhất 5 ký tự', value => {
            if (!value) return true;
            return value.trim().length === 0 || value.trim().length >= 5;
        }),
});

function onSubmit() {
    emit('confirmed', {
        approvalNote: (form.approvalNote || '').trim()
    });
}
</script>

<style scoped>
.invalid-feedback {
    display: block;
}
</style>