<template>
    <div class="row">
        <div class="col">
            <loading-component style="height: 50px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>
            <div class="row" v-show="!isLoading">
                <div class="col">
                    <div class="row m-b-20">
                        <div class="col">
                            <h6 class="all-caps m-b-5 bold no-margin">{{ parameters.id ? 'Update Affiliate Code' : 'Create Affiliate Code' }}</h6>
                        </div>
                    </div>
                    <div class="row m-b-5 animate__animated animate__fadeInUpBig animate__fast" v-if="error">
                        <div class="col">
                            <small class="bold fs-10 text-danger">{{ error }}</small>
                        </div>
                    </div>
                    <div class="row m-b-10">
                        <div class="col">
                            <input type="hidden" class="form-control" v-if="parameters.id" v-model="parameters.id">
                            <validation-wrapper-component :validator="v$.parameters.campaign_name">
                                <label>Campaign Name</label>
                                <input type="text" class="form-control" v-model="parameters.campaign_name" placeholder="e.g., Summer Campaign 2024">
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row m-b-10">
                        <div class="col">
                            <validation-wrapper-component :validator="v$.parameters.code">
                                <label>Code</label>
                                <input type="text" class="form-control" v-model="parameters.code" placeholder="e.g., SUMMER2024" :disabled="!!parameters.id">
                                <small class="hint-text" v-if="!parameters.id">Leave empty to auto-generate a unique code</small>
                                <small class="hint-text" v-if="parameters.id">Code cannot be changed after creation</small>
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row m-b-10">
                        <div class="col">
                            <validation-wrapper-component :validator="v$.parameters.campaign_description">
                                <label>Campaign Description</label>
                                <textarea class="form-control" v-model="parameters.campaign_description" rows="3" placeholder="Optional description for this affiliate campaign"></textarea>
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row m-b-10">
                        <div class="col">
                            <label>Is Active</label>
                            <div class="row m-t-5">
                                <div class="col-auto">
                                    <div class="pointer" @click="parameters.is_active = !parameters.is_active">
                                        <div class="row align-items-center">
                                            <div class="col-auto p-r-10">
                                                <div class="icon-thumbnail fs-12 icon-30 btn-rounded" :class="[{ 'bg-success': parameters.is_active }, { 'bg-master-light': !parameters.is_active }]">
                                                    <i class="fa fa-check fs-12 text-white" v-if="parameters.is_active"></i>
                                                </div>
                                            </div>
                                            <div class="col p-l-0">
                                                <div class="font-heading fs-10" :class="[{ 'text-success': parameters.is_active }, { 'text-muted': !parameters.is_active }]">
                                                    {{ parameters.is_active ? 'Active' : 'Inactive' }}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row m-b-20" v-if="parameters.id && trackingLink">
                        <div class="col">
                            <label>Tracking Link</label>
                            <div class="input-group">
                                <input type="text" class="form-control" :value="trackingLink" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-sm btn-default" @click="copyLink" type="button">
                                        <i class="fa fa-copy"></i> Copy
                                    </button>
                                </div>
                            </div>
                        </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">{{ parameters.id ? 'Update' : 'Create' }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { computed, watch } from 'vue';
import { useFormHandler } from '@/composables/useFormHandler';
import { useQueueStore } from '@/stores/queue';
import { useNotificationStore } from '@/stores/notification';
import route from '@/general/functions/router';
import { useVuelidate } from '@vuelidate/core';
import { required } from '@vuelidate/validators';

interface Props {
    section: string;
    data?: any;
}

const props = defineProps<Props>();
const queueStore = useQueueStore();
const notificationStore = useNotificationStore();

const { parameters, submit, error, isLoading, closeModal } = useFormHandler({
    section: props.section,
    data: null
});

const normalizeIsActive = (value: any): boolean => {
    if (value === false || value === 'false' || value === 0 || value === '0') return false;
    if (value === true || value === 'true' || value === 1 || value === '1') return true;
    return true;
};

const resetForm = () => {
    v$.value.$reset();
    resetFormState();
};

const resetFormState = () => {
    parameters.value = {
        id: null,
        campaign_name: '',
        code: '',
        campaign_description: '',
        is_active: true
    };
};

watch(
    () => props.data,
    (newData) => {
        if (newData) {
            const cloned = JSON.parse(JSON.stringify(newData));
            cloned.is_active = normalizeIsActive(cloned.is_active);
            parameters.value = cloned;
        } else {
            resetFormState();
        }
    },
    { deep: true, immediate: true }
);

const rules = {
    parameters: {
        campaign_name: { required },
        code: {},
        campaign_description: {},
        is_active: {}
    }
};

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

const trackingLink = computed(() => {
    if (parameters.value.id && parameters.value.code) {
        return `${window.location.origin}/signup?tracking=${parameters.value.code}`;
    }
    return null;
});

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

    const endpoint = parameters.value.id
        ? route('api.affiliate.update', parameters.value.id)
        : route('api.affiliate.create');
    const method = parameters.value.id ? 'put' : 'post';

    await submit(endpoint, method, props.section, true, false, parameters.value, {
        successHandler: () => {
            closeModal();
            resetForm();
            queueStore.reloadList({ name: 'affiliatesSection' });
        }
    });
};

const copyLink = async () => {
    if (!trackingLink.value) return;

    await navigator.clipboard.writeText(trackingLink.value);
    notificationStore.createNotification({
        title: 'Success',
        message: 'Tracking link copied to clipboard',
        type: 'success'
    });
};
</script>
