<script lang="ts" setup>
import { BccButton, BccFormMessage, BccModal } from '@bcc-code/design-library-vue';
import { localize } from '@cometchat/uikit-resources';
import { computed, onMounted, ref } from 'vue';

const props = defineProps({
    isReschedule: { type: Boolean, default: false },
    closeOnOutsideClick: { type: Boolean, default: true }
})

const title = props.isReschedule ? localize("RESCHEDULE") : localize("SCHEDULE_MESSAGE")
const closeOnOutsideClick = ref<boolean>(props.closeOnOutsideClick);
const emit = defineEmits(['close', 'schedule', 'reschedule']);

const dateInput = ref<string>();
const timeInput = ref<string>();
const messageSent = ref<boolean>(false);

const localDateTime = computed<string>(() => {
    return new Date(dateInput.value + "T" + timeInput.value).toISOString()
})

const isDateInFuture = computed<boolean>(() => {
    if (dateInput.value === '' || timeInput.value === '') return false
    return new Date(localDateTime.value) > new Date();
})

onMounted(() => {
    const now = new Date();

    dateInput.value = now.toISOString().split('T')[0];
    now.setHours(now.getHours() + 1); // Add 1 hour
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    timeInput.value = `${hours}:${minutes}`;

    setTimeout(() => closeOnOutsideClick.value = true, 500);
})

function close() {
    emit('close');
}

function scheduleMessage() {
    if (isDateInFuture && !messageSent.value) {
        emit(props.isReschedule ? 'reschedule' : 'schedule', localDateTime.value)
        messageSent.value = true;
    }
}
</script>

<template>
    <BccModal class="modal" :title="title" :open="true" @close="close()" :closeOnOutsideClick="closeOnOutsideClick"
        :closeButton="true">
        <div class="flex flex-col w-full">
            <div class="flex w-full items-center justify-between">
                <input class="bcc-input text-right justify-end" type="date" v-model="dateInput" required />
                <p class="mx-2">{{ localize("AT") }}</p>
                <input class="bcc-input text-right justify-end" type="time" v-model="timeInput" required />
            </div>
            <BccFormMessage class="text-center mt-2 mb-0 text-red-500" v-if="!isDateInFuture" state="error">
                {{ localize("ERROR_DATE_IN_FUTURE") }}
            </BccFormMessage>
        </div>

        <template #primaryAction>
            <BccButton class="button" :disabled="messageSent" @click="scheduleMessage()">
                {{ localize("SCHEDULE_MESSAGE") }}
            </BccButton>
        </template>
    </BccModal>
</template>