<template>

    <div class="subscriptionsStatus" :class="[classes]">

        <div class="subscriptionsStatus__dates" v-if="isActive && (nextIssueDate?.length || nextPaymentDate?.length)">

            <div class="subscriptionsStatus__dateCard" v-if="nextPaymentDate?.length">
                <i class="fas fa-credit-card subscriptionsStatus__dateIcon"></i>
                <div class="subscriptionsStatus__dateInfo">
                    <span class="subscriptionsStatus__dateLabel">Next payment</span>
                    <span class="subscriptionsStatus__dateValue" v-html="displayPaymentDate"></span>
                </div>
            </div>

            <div class="subscriptionsStatus__dateCard" v-if="nextIssueDate?.length">
                <i class="fas fa-truck subscriptionsStatus__dateIcon"></i>
                <div class="subscriptionsStatus__dateInfo">
                    <span class="subscriptionsStatus__dateLabel">Next dispatch</span>
                    <span class="subscriptionsStatus__dateValue">
                        <span v-html="displayIssueDate"></span>
                        <a href="#" class="subscriptionsStatus__editLink" @click.prevent="toggleEditIssueDate" title="Change dispatch date">
                            <i class="fas fa-pencil-alt"></i>
                        </a>
                    </span>
                </div>
            </div>

        </div>

        <div class="subscriptionsStatus__editArea" v-show="editVisible">

            <div class="row subscriptionsStatus__editAreaField">

                <label :for="'subscription-date-' + componentId">
                    Edit next dispatch date
                </label>

                <date-text-field
                        v-model="newIssueDate"
                        :id="'subscription-date-' + componentId"
                        :always-emit="true"
                ></date-text-field>

            </div>

            <div class="subscriptionsStatus__editAreaButtons" :class="[loading ? 'subscriptionsStatus__editAreaButtons--loading' : '']">

                <a
                        href="#"
                        class="subscriptionsStatus__editAction subscriptionsStatus__editAction--save"
                        @click.prevent="updateNextIssueDate"
                >
                    <i class="fas fa-check"></i> Save
                </a>

                <a
                        href="#"
                        class="subscriptionsStatus__editAction subscriptionsStatus__editAction--cancel"
                        @click.prevent="closeEditBox"
                >
                    <i class="fas fa-times"></i> Cancel
                </a>

            </div>

            <div
                    class="subscriptionsStatus__message"
                    v-show="message.msg?.length && message.type?.length"
            >
                <div
                        class="subscriptionsStatus__messageContent"
                        :class="['subscriptionsStatus__messageContent--' + message.type]"
                        v-text="message.msg"
                ></div>
            </div>



        </div> <!-- .__editArea -->

    </div>

</template>

<script>

import axios from 'axios';

export default {

    props: {

        updateUrl: {
            type: [String],
            default() {
                return '';
            }
        },

        status: {
            type: [String],
            default() {
                return '';
            }
        },

        setNextIssueDate: {
            type: [String],
            default() {
                return '';
            }
        },

        setNextPaymentDate: {
            type: [String],
            default() {
                return '';
            }
        },

        classes: {
            type: [String],
            default() {
                return '';
            }
        }

    },

    data() {

        return {
            componentId: Math.random().toString(36).substr(2, 9),
            nextIssueDate: '',
            nextPaymentDate: '',
            nextIssueDateDisplay: '',
            nextPaymentDateDisplay: '',
            editVisible: false,
            newIssueDate: '',
            loading: false,
            message: {
                type: '',
                msg: ''
            }
        }

    },

    created() {

        //Set issue and payment dates
        this.nextIssueDate = this.setNextIssueDate;
        this.nextPaymentDate = this.setNextPaymentDate;

        this.nextIssueDateDisplay = this.setNextIssueDate;
        this.nextPaymentDateDisplay = this.setNextPaymentDate;

        //Set new issue date default
        this.newIssueDate = this.nextIssueDate;

    },

    computed: {

        displayIssueDate() {
            return this.formatDate(this.nextIssueDateDisplay);
        },
        displayPaymentDate() {
            return this.formatDate(this.nextPaymentDateDisplay);
        },

        isActive() {
            return this.status.toLowerCase() === 'active';
        }

    },

    methods: {

        updateNextIssueDate() {

            const vm = this;
            this.loading = true;

            const [year, month, day] = vm.newIssueDate.split('-');
            const formattedDate = `${day}/${month}/${year}`;
            axios.post(vm.updateUrl, { next_issue_date: formattedDate }).then(function (response) {

                if(response.data?.error?.length) {

                    const error = response.data.error;
                    vm.setMessage(error, true);

                }else{

                    if(response.data?.success?.length) {
                        const success = response.data.success;
                        vm.setMessage(success, false);

                        if(response.data?.next_issue_date?.length) {
                            vm.nextIssueDateDisplay = response.data.next_issue_date;
                        }
                        if(response.data?.next_payment_date?.length) {
                            vm.nextPaymentDateDisplay = response.data.next_payment_date;
                        }
                    }
                }

            })
            .catch(function (error) {
                const msg = error.response?.data?.error || 'Something went wrong. Please try again.';
                vm.setMessage(msg, true);
            })
            .finally(function () {
                vm.loading = false;
            });

        },

        formatDate(date) {
            if (!date) return '';
            // Already in DD/MM/YYYY format
            if (/^\d{2}\/\d{2}\/\d{4}$/.test(date)) return date;
            // YYYY-MM-DD format
            if (/^\d{4}-\d{2}-\d{2}/.test(date)) {
                const [year, month, day] = date.substring(0, 10).split('-');
                return `${day}/${month}/${year}`;
            }
            return date;
        },

        setMessage(message, error) {

            if(error) {
                this.message.type = 'error';
            }else{
                this.message.type = 'success';
            }

            if(message.length) {
                this.message.msg = message;
            }else{
                this.message.msg = '';
            }

        },

        resetForm() {
            this.message.type = '';
            this.message.msg = '';
        },

        capitalize(str) {
            return str.charAt(0).toUpperCase() + str.slice(1);
        },

        toggleEditIssueDate() {
            this.editVisible = !this.editVisible;

            if(!this.editVisible) {
                this.resetForm();
            }
        },

        closeEditBox() {
            this.editVisible = false;
            this.resetForm();
        }

    }

}
</script>

<style lang="less">

    @import '@site/css/variables.less';
    @import '@core/css/mixins.less';
    @import '@site/../default/css/base/mixins.less';

    .subscriptionsStatus {

        &__dates {
            display: flex;
            gap: 16px;
            margin-bottom: 16px;

            @media @mobile {
                flex-direction: column;
            }
        }

        &__dateCard {
            display: flex;
            align-items: center;
            gap: 12px;
            background: var(--light_color, #f8f9fa);
            border: 1px solid var(--border_color, #dee2e6);
            border-radius: 6px;
            padding: 12px 16px;
            flex: 1;
        }

        &__dateIcon {
            .rems(20);
            color: var(--highlight_color, #226B64);
            flex-shrink: 0;
        }

        &__dateInfo {
            display: flex;
            flex-direction: column;
        }

        &__dateLabel {
            .rems(12);
            color: var(--text_color, #333);
            opacity: 0.7;
            line-height: 1.2;
        }

        &__dateValue {
            .rems(15);
            font-weight: 600;
            line-height: 1.4;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        &__editLink {
            .rems(13);
            color: var(--highlight_color, #226B64);
            opacity: 0.6;
            transition: opacity 200ms;

            &:hover {
                opacity: 1;
            }
        }

        &__editArea {
            border-top: 1px solid rgba(0,0,0,0.08);
            padding-top: 12px;
            margin-top: 12px;
        }

        &__editAreaButtons {
            display: flex;
            gap: 16px;
            align-items: center;
            margin-top: 8px;
            opacity: 1;
            pointer-events: auto;
            transition: opacity 300ms;

            &--loading {
                opacity: 0.5;
                pointer-events: none;
                transition: opacity 300ms;
            }
        }

        &__editAction {
            .rems(13);
            font-weight: 500;
            text-decoration: none;
            transition: opacity 200ms;

            &--save {
                color: var(--highlight_color, #226B64);
            }

            &--cancel {
                color: var(--text_color, #333);
                opacity: 0.5;

                &:hover {
                    opacity: 0.8;
                }
            }

            i {
                margin-right: 2px;
            }
        }

        &__message {

        }

        &__messageContent {

            &--success {
                color: @success_color;
            }

            &--error {
                color: @alert_color;
            }
        }

    }

</style>
